[clang] [Clang][InstrProf] Allow mix-up of absolute path with relative path on command line when using -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits

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


[clang] [Clang][InstrProf] Allow mix-up of absolute path with relative path on command line when using -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits

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


[clang] [Clang][InstrProf] Allow mix-up of absolute path with relative path on command line when using -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits

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


[clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71755)

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

owenca wrote:

> However this doesn't address the second part of the linked issue (with the 
> `if`) does it?

Nope! That part is a duplicate of #64474. I was going to add a note in #71563 
before merging this PR but now just saw that @FalcoGer closed the old issue and 
opened the new one, which is essentially the same.

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


[clang] Llvm modules on demand bmi (PR #71773)

2023-11-08 Thread Iain Sandoe via cfe-commits

iains wrote:


> There are 2 things in the patch. One is to generate the BMI and the object 
> file in one phase (phase here means preprocess, precompile, compile, ...). 

This is the main point of the patch - to do this efficiently.

>Another is to allow us to generate BMI from a `.cpp` file. (Currently we only 
>do this for `.cppm` file or `-x c++-module` file).

Please do not become distracted by this, it is a side-effect of the main 
purpose, if the community wants to have modular files with some specific 
suffix, the patch still works the same.

> But after we introduced thin BMI, it looks inefficient to write the AST 
> twice. So it is on my TODO list after we land the thin BMI patch. BTW, I 
> think we should do thin in CodeGen action instead of hacking on 
> WrappedASTConsumer.

I am curious as to why you think that the multiplex AST consumer is a hack - it 
seems to be designed exactly for this purpose and existed already (i.e. not 
part of this patch).


> For the second thing, I am curious that if it is necessary now? Or what will 
> it block? I mean, the build systems or the cmake, require to mark the module 
> unit ahead of time. Then the build systems will pass `-x c++-module` now for 
> module units. Then the suffixes are not a thing for users.

I think you are getting distracted by the suffix; that is only a side-effect of 
this patch, not its primary purpose.


> And to me, the current mechanism for `.cppm` (or `-x c++-module`) in the 
> driver side works pretty well. 

I have always viewed that as a temporary work-around because we could not 
generate both artefacts from one compiler invocation.

>And if we introduce the mechanism to produce BMI for `.cpp`, it implies that 
>we need to maintain both paths. It is super embracing to me.

We do not need two mechanisms, .cppm can take the same path as any other suffix.

> > in the AST consumer on the BMI side doing suitable filtering to eliminate 
> > the content that is not part of the interface, that is either not needed 
> > (or in some cases positively unhelpful to consumers).

 
> I believe we should do this in ASTWriters.

I am strongly against doing more semantic work in the AST reader/writer; that 
is just compounding existing layering violations that are already hurting us.

> Also this should be part of thin BMI.

I am not sure what you mean here - the full AST is required for code-gen - we 
can only thin AST either on a separate path (as in this patch) or as a separate 
step.


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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2023-11-08 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Oh, I didn't look into the identifier's system before. I took a while to look 
at the patch but I failed to understand it and I failed to find the 
relationships between this patch and header units... 

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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2023-11-08 Thread Chuanqi Xu via cfe-commits


@@ -86,19 +87,26 @@ enum { IdentifierInfoAlignment = 8 };
 static constexpr int ObjCOrBuiltinIDBits = 16;
 
 /// The "layout" of ObjCOrBuiltinID is:
-///  - The first value (0) represents "not a special identifier".
-///  - The next (NUM_OBJC_KEYWORDS - 1) values represent ObjCKeywordKinds (not
-///including objc_not_keyword).
-///  - The next (NUM_INTERESTING_IDENTIFIERS - 1) values represent
-///InterestingIdentifierKinds (not including not_interesting).
-///  - The rest of the values represent builtin IDs (not including NotBuiltin).
-static constexpr int FirstObjCKeywordID = 1;
-static constexpr int LastObjCKeywordID =
-FirstObjCKeywordID + tok::NUM_OBJC_KEYWORDS - 2;
-static constexpr int FirstInterestingIdentifierID = LastObjCKeywordID + 1;
-static constexpr int LastInterestingIdentifierID =
-FirstInterestingIdentifierID + tok::NUM_INTERESTING_IDENTIFIERS - 2;
-static constexpr int FirstBuiltinID = LastInterestingIdentifierID + 1;
+///  - ObjCKeywordKind enumerators
+///  - InterestingIdentifierKind enumerators
+///  - Builtin::ID enumerators
+///  - NonSpecialIdentifier
+enum class ObjCKeywordOrInterestingOrBuiltin {
+#define OBJC_AT_KEYWORD(X) objc_##X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS,

ChuanqiXu9 wrote:

It looks like we have `tok::NUM_OBJC_KEYWORDS` and 
`ObjCKeywordOrInterestingOrBuiltin::NUM_OBJC_KEYWORDS` now. And it smells not 
good to have them with the same name.

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


[clang] [Clang][InstrProf] Allow mix-up of absolute path with relative path on command line when using -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits

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


[clang] [clang][dataflow][NFC] Fix stale comments. (PR #71654)

2023-11-08 Thread via cfe-commits

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


[clang] ae74370 - [clang][dataflow][NFC] Fix stale comments. (#71654)

2023-11-08 Thread via cfe-commits

Author: martinboehme
Date: 2023-11-09T08:39:06+01:00
New Revision: ae743705113d5ec818517aefa94e704a1257ec95

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

LOG: [clang][dataflow][NFC] Fix stale comments. (#71654)

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/Arena.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/Arena.h 
b/clang/include/clang/Analysis/FlowSensitive/Arena.h
index 4be308c43fb7675..394ce054e65f11c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Arena.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Arena.h
@@ -29,8 +29,8 @@ class Arena {
   /// Creates a `T` (some subclass of `StorageLocation`), forwarding `args` to
   /// the constructor, and returns a reference to it.
   ///
-  /// The `DataflowAnalysisContext` takes ownership of the created object. The
-  /// object will be destroyed when the `DataflowAnalysisContext` is destroyed.
+  /// The `Arena` takes ownership of the created object. The object will be
+  /// destroyed when the `Arena` is destroyed.
   template 
   std::enable_if_t::value, T &>
   create(Args &&...args) {
@@ -45,8 +45,8 @@ class Arena {
   /// Creates a `T` (some subclass of `Value`), forwarding `args` to the
   /// constructor, and returns a reference to it.
   ///
-  /// The `DataflowAnalysisContext` takes ownership of the created object. The
-  /// object will be destroyed when the `DataflowAnalysisContext` is destroyed.
+  /// The `Arena` takes ownership of the created object. The object will be
+  /// destroyed when the `Arena` is destroyed.
   template 
   std::enable_if_t::value, T &>
   create(Args &&...args) {



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


[clang] 427f13b - [NFC] [C++20] [Modules] Remove 'ModuleInterface' bit in Sema::ModuleScope

2023-11-08 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-11-09T15:20:32+08:00
New Revision: 427f13bd724d332681ca5adb2455b7241af7177d

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

LOG: [NFC] [C++20] [Modules] Remove 'ModuleInterface' bit in Sema::ModuleScope

The 'ModuleInterface' in Sema::ModuleScope is confusing. It actually
means 'not implementation'. This patch removes that bit and extract the
information from the recorded clang::Module.

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaModule.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index a8c41492b61ac4c..fe8b387f198c56e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2303,7 +2303,6 @@ class Sema final {
   struct ModuleScope {
 SourceLocation BeginLoc;
 clang::Module *Module = nullptr;
-bool ModuleInterface = false;
 VisibleModuleSet OuterVisibleModules;
   };
   /// The modules we're currently parsing.
@@ -2367,9 +2366,11 @@ class Sema final {
 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
   }
 
-  /// Is the module scope we are an interface?
-  bool currentModuleIsInterface() const {
-return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
+  /// Is the module scope we are an implementation unit?
+  bool currentModuleIsImplementation() const {
+return ModuleScopes.empty()
+   ? false
+   : ModuleScopes.back().Module->isModuleImplementation();
   }
 
   /// Is the module scope we are in a C++ Header Unit?

diff  --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index 8a296837e2a192c..99b4d7d0fe40ee3 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -125,7 +125,6 @@ void Sema::HandleStartOfHeaderUnit() {
   ModuleScopes.push_back({}); // No GMF
   ModuleScopes.back().BeginLoc = StartOfTU;
   ModuleScopes.back().Module = Mod;
-  ModuleScopes.back().ModuleInterface = true;
   VisibleModules.setVisible(Mod, StartOfTU);
 
   // From now on, we have an owning module for all declarations we see.
@@ -375,7 +374,6 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, 
SourceLocation ModuleLoc,
   // Switch from the global module fragment (if any) to the named module.
   ModuleScopes.back().BeginLoc = StartLoc;
   ModuleScopes.back().Module = Mod;
-  ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
   VisibleModules.setVisible(Mod, ModuleLoc);
 
   // From now on, we have an owning module for all declarations we see.
@@ -470,7 +468,6 @@ Sema::ActOnPrivateModuleFragmentDecl(SourceLocation 
ModuleLoc,
   ModuleScopes.push_back({});
   ModuleScopes.back().BeginLoc = ModuleLoc;
   ModuleScopes.back().Module = PrivateModuleFragment;
-  ModuleScopes.back().ModuleInterface = true;
   VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
 
   // All declarations created from now on are scoped to the private module
@@ -523,7 +520,7 @@ DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
   getCurrentModule()->Name == ModuleName) {
 Diag(ImportLoc, diag::err_module_self_import_cxx20)
-<< ModuleName << !ModuleScopes.back().ModuleInterface;
+<< ModuleName << currentModuleIsImplementation();
 return true;
   }
 
@@ -609,10 +606,7 @@ DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
   Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
 Diag(ExportLoc, diag::err_export_partition_impl)
 << SourceRange(ExportLoc, Path.back().second);
-  } else if (!ModuleScopes.empty() &&
- (ModuleScopes.back().ModuleInterface ||
-  (getLangOpts().CPlusPlusModules &&
-   ModuleScopes.back().Module->isGlobalModule( {
+  } else if (!ModuleScopes.empty() && !currentModuleIsImplementation()) {
 // Re-export the module if the imported module is exported.
 // Note that we don't need to add re-exported module to Imports field
 // since `Exports` implies the module is imported already.
@@ -772,7 +766,7 @@ Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation 
ExportLoc,
 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
 D->setInvalidDecl();
 return D;
-  } else if (!ModuleScopes.back().ModuleInterface) {
+  } else if (currentModuleIsImplementation()) {
 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
 Diag(ModuleScopes.back().BeginLoc,
  diag::note_not_module_interface_add_export)
@@ -932,7 +926,6 @@ Module *Sema::PushGlobalModuleFragment(SourceLocation 
BeginLoc) {
 
   // Enter the scope of the global module.
   

[clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71755)

2023-11-08 Thread Emilia Kond via cfe-commits

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

However this doesn't address the second part of the linked issue (with the 
`if`) does it?

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


[lldb] [clang] Reland "[clang][DebugInfo] Emit global variable definitions for static data members with constant initializers" (PR #71780)

2023-11-08 Thread Michael Buch via cfe-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/71780

>From e5bc858c35b479d29174c9945c6c67f4d2dc085b Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Thu, 9 Nov 2023 01:13:21 +
Subject: [PATCH 1/2] Reland "[clang][DebugInfo] Emit global variable
 definitions for static data members with constant initializers"

---
 clang/lib/CodeGen/CGDebugInfo.cpp | 58 +++
 clang/lib/CodeGen/CGDebugInfo.h   |  6 ++
 clang/test/CodeGenCXX/debug-info-class.cpp| 13 +++--
 .../CodeGenCXX/debug-info-static-member.cpp   | 52 ++---
 .../TestConstStaticIntegralMember.py  |  7 ++-
 .../lldb-dap/variables/TestDAP_variables.py   |  9 +--
 6 files changed, 103 insertions(+), 42 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 84a166d3ac3659c..245f7516640d098 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1677,22 +1677,13 @@ CGDebugInfo::CreateRecordStaticField(const VarDecl 
*Var, llvm::DIType *RecordTy,
 
   unsigned LineNumber = getLineNumber(Var->getLocation());
   StringRef VName = Var->getName();
-  llvm::Constant *C = nullptr;
-  if (Var->getInit()) {
-const APValue *Value = Var->evaluateValue();
-if (Value) {
-  if (Value->isInt())
-C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
-  if (Value->isFloat())
-C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
-}
-  }
 
   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
-  RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
+  RecordTy, VName, VUnit, LineNumber, VTy, Flags, /* Val */ nullptr, 
Align);
   StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
+  StaticDataMemberDefinitionsToEmit.push_back(Var->getCanonicalDecl());
   return GV;
 }
 
@@ -5596,6 +5587,39 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl 
*VD, const APValue ) {
   TemplateParameters, Align));
 }
 
+void CGDebugInfo::EmitGlobalVariable(const VarDecl *VD) {
+  assert(VD->hasInit());
+  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  if (VD->hasAttr())
+return;
+
+  auto  = DeclCache[VD];
+  if (GV)
+return;
+
+  auto const *InitVal = VD->evaluateValue();
+  if (!InitVal)
+return;
+
+  llvm::DIFile *Unit = nullptr;
+  llvm::DIScope *DContext = nullptr;
+  unsigned LineNo;
+  StringRef DeclName, LinkageName;
+  QualType T;
+  llvm::MDTuple *TemplateParameters = nullptr;
+  collectVarDeclProps(VD, Unit, LineNo, T, DeclName, LinkageName,
+  TemplateParameters, DContext);
+
+  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
+  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
+  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, *InitVal);
+
+  GV.reset(DBuilder.createGlobalVariableExpression(
+  TheCU, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
+  true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VD),
+  TemplateParameters, Align, Annotations));
+}
+
 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
const VarDecl *D) {
   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
@@ -5800,6 +5824,18 @@ void CGDebugInfo::setDwoId(uint64_t Signature) {
 }
 
 void CGDebugInfo::finalize() {
+  for (auto const *VD : StaticDataMemberDefinitionsToEmit) {
+assert(VD->isStaticDataMember());
+
+if (DeclCache.contains(VD))
+  continue;
+
+if (!VD->hasInit())
+  continue;
+
+EmitGlobalVariable(VD);
+  }
+
   // Creating types might create further types - invalidating the current
   // element and the size(), so don't cache/reference them.
   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 7b60e94555d0608..3e4c133b7f2b9f1 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -161,6 +161,9 @@ class CGDebugInfo {
   llvm::DenseMap>
   StaticDataMemberCache;
 
+  /// Keeps track of static data members for which we should emit a definition.
+  std::vector StaticDataMemberDefinitionsToEmit;
+
   using ParamDecl2StmtTy = llvm::DenseMap;
   using Param2DILocTy =
   llvm::DenseMap;
@@ -526,6 +529,9 @@ class CGDebugInfo {
   /// Emit a constant global variable's debug info.
   void EmitGlobalVariable(const ValueDecl *VD, const APValue );
 
+  /// Emit debug-info for a variable with a constant initializer.
+  void EmitGlobalVariable(const VarDecl *VD);
+
   /// Emit information about an external variable.
   void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
 
diff --git a/clang/test/CodeGenCXX/debug-info-class.cpp 

[lldb] [clang] Reland "[clang][DebugInfo] Emit global variable definitions for static data members with constant initializers" (PR #71780)

2023-11-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Michael Buch (Michael137)


Changes

This patch relands https://github.com/llvm/llvm-project/pull/70639

It was reverted because under certain conditions we triggered an assertion
in `DIBuilder`. Specifically, in the original patch we called 
`EmitGlobalVariable`
at the end of `CGDebugInfo::finalize`, after all the temporary `DIType`s have
been uniqued. With limited debug-info such temporary nodes would be created
more frequently, leaving us with non-uniqued nodes by the time we got to
`DIBuilder::finalize`; this violated its pre-condition and caused
assertions to trigger.

To fix this, the latest iteration of the patch moves `EmitGlobalVariable` to the
beginning of `CGDebugInfo::finalize`. Now, when we create a temporary
`DIType` node as a result of emitting a variable definition, it will get uniqued
in time. A test-case was added for this scenario.

Original commit message:
"""
When an LLDB user asks for the value of a static data member, LLDB starts
by searching the Names accelerator table for the corresponding variable
definition DIE. For static data members with out-of-class definitions that
works fine, because those get represented as global variables with a location
and making them eligible to be added to the Names table. However, in-class
definitions won’t get indexed because we usually don't emit global variables
for them. So in DWARF we end up with a single `DW_TAG_member` that
usually holds the constant initializer.  But we don't get a corresponding
CU-level `DW_TAG_variable` like we do for out-of-class definitions.

To make it more convenient for debuggers to get to the value of inline static 
data
members, this patch makes sure we emit definitions for static variables with
constant initializers the same way we do for other static variables. This also 
aligns
Clang closer to GCC, which produces CU-level definitions for inline statics and 
also
emits these into `.debug_pubnames`.

The implementation keeps track of newly created static data members.
Then in `CGDebugInfo::finalize`, we emit a global `DW_TAG_variable` with a
`DW_AT_const_value` for any of those declarations that didn't end up with a
definition in the `DeclCache`.

The newly emitted `DW_TAG_variable` will look as follows:
```
0x007b:   DW_TAG_structure_type
DW_AT_calling_convention(DW_CC_pass_by_value)
DW_AT_name  ("Foo")
...

0x008d: DW_TAG_member
  DW_AT_name("i")
  DW_AT_type(0x0062 "const int")
  DW_AT_external(true)
  DW_AT_declaration (true)
  DW_AT_const_value (4)

Newly added
v

0x009a:   DW_TAG_variable
DW_AT_specification (0x008d "i")
DW_AT_const_value   (4)
DW_AT_linkage_name  ("_ZN2t2IiE1iIfEE")
```

This patch also drops the `DW_AT_const_value` off of the declaration since we
now always have it on the definition. This ensures that the 
`DWARFParallelLinker`
can type-merge class with static members where we couldn't attach the constant
on the declaration in some CUs.
"""

Dependent changes:
* https://github.com/llvm/llvm-project/pull/71004
* https://github.com/llvm/llvm-project/pull/70641

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


6 Files Affected:

- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+47-11) 
- (modified) clang/lib/CodeGen/CGDebugInfo.h (+6) 
- (modified) clang/test/CodeGenCXX/debug-info-class.cpp (+9-4) 
- (modified) clang/test/CodeGenCXX/debug-info-static-member.cpp (+32-20) 
- (modified) 
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
 (+4-3) 
- (modified) lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py (+5-4) 


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 84a166d3ac3659c..245f7516640d098 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1677,22 +1677,13 @@ CGDebugInfo::CreateRecordStaticField(const VarDecl 
*Var, llvm::DIType *RecordTy,
 
   unsigned LineNumber = getLineNumber(Var->getLocation());
   StringRef VName = Var->getName();
-  llvm::Constant *C = nullptr;
-  if (Var->getInit()) {
-const APValue *Value = Var->evaluateValue();
-if (Value) {
-  if (Value->isInt())
-C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
-  if (Value->isFloat())
-C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
-}
-  }
 
   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
-  RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
+  RecordTy, VName, VUnit, 

[lldb] [clang] Reland "[clang][DebugInfo] Emit global variable definitions for static data members with constant initializers" (PR #71780)

2023-11-08 Thread Michael Buch via cfe-commits

https://github.com/Michael137 created 
https://github.com/llvm/llvm-project/pull/71780

This patch relands https://github.com/llvm/llvm-project/pull/70639

It was reverted because under certain conditions we triggered an assertion
in `DIBuilder`. Specifically, in the original patch we called 
`EmitGlobalVariable`
at the end of `CGDebugInfo::finalize`, after all the temporary `DIType`s have
been uniqued. With limited debug-info such temporary nodes would be created
more frequently, leaving us with non-uniqued nodes by the time we got to
`DIBuilder::finalize`; this violated its pre-condition and caused
assertions to trigger.

To fix this, the latest iteration of the patch moves `EmitGlobalVariable` to the
beginning of `CGDebugInfo::finalize`. Now, when we create a temporary
`DIType` node as a result of emitting a variable definition, it will get uniqued
in time. A test-case was added for this scenario.

Original commit message:
"""
When an LLDB user asks for the value of a static data member, LLDB starts
by searching the Names accelerator table for the corresponding variable
definition DIE. For static data members with out-of-class definitions that
works fine, because those get represented as global variables with a location
and making them eligible to be added to the Names table. However, in-class
definitions won’t get indexed because we usually don't emit global variables
for them. So in DWARF we end up with a single `DW_TAG_member` that
usually holds the constant initializer.  But we don't get a corresponding
CU-level `DW_TAG_variable` like we do for out-of-class definitions.

To make it more convenient for debuggers to get to the value of inline static 
data
members, this patch makes sure we emit definitions for static variables with
constant initializers the same way we do for other static variables. This also 
aligns
Clang closer to GCC, which produces CU-level definitions for inline statics and 
also
emits these into `.debug_pubnames`.

The implementation keeps track of newly created static data members.
Then in `CGDebugInfo::finalize`, we emit a global `DW_TAG_variable` with a
`DW_AT_const_value` for any of those declarations that didn't end up with a
definition in the `DeclCache`.

The newly emitted `DW_TAG_variable` will look as follows:
```
0x007b:   DW_TAG_structure_type
DW_AT_calling_convention(DW_CC_pass_by_value)
DW_AT_name  ("Foo")
...

0x008d: DW_TAG_member
  DW_AT_name("i")
  DW_AT_type(0x0062 "const int")
  DW_AT_external(true)
  DW_AT_declaration (true)
  DW_AT_const_value (4)

Newly added
v

0x009a:   DW_TAG_variable
DW_AT_specification (0x008d "i")
DW_AT_const_value   (4)
DW_AT_linkage_name  ("_ZN2t2IiE1iIfEE")
```

This patch also drops the `DW_AT_const_value` off of the declaration since we
now always have it on the definition. This ensures that the 
`DWARFParallelLinker`
can type-merge class with static members where we couldn't attach the constant
on the declaration in some CUs.
"""

Dependent changes:
* https://github.com/llvm/llvm-project/pull/71004
* https://github.com/llvm/llvm-project/pull/70641

>From e5bc858c35b479d29174c9945c6c67f4d2dc085b Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Thu, 9 Nov 2023 01:13:21 +
Subject: [PATCH] Reland "[clang][DebugInfo] Emit global variable definitions
 for static data members with constant initializers"

---
 clang/lib/CodeGen/CGDebugInfo.cpp | 58 +++
 clang/lib/CodeGen/CGDebugInfo.h   |  6 ++
 clang/test/CodeGenCXX/debug-info-class.cpp| 13 +++--
 .../CodeGenCXX/debug-info-static-member.cpp   | 52 ++---
 .../TestConstStaticIntegralMember.py  |  7 ++-
 .../lldb-dap/variables/TestDAP_variables.py   |  9 +--
 6 files changed, 103 insertions(+), 42 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 84a166d3ac3659c..245f7516640d098 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1677,22 +1677,13 @@ CGDebugInfo::CreateRecordStaticField(const VarDecl 
*Var, llvm::DIType *RecordTy,
 
   unsigned LineNumber = getLineNumber(Var->getLocation());
   StringRef VName = Var->getName();
-  llvm::Constant *C = nullptr;
-  if (Var->getInit()) {
-const APValue *Value = Var->evaluateValue();
-if (Value) {
-  if (Value->isInt())
-C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
-  if (Value->isFloat())
-C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
-}
-  }
 
   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
   llvm::DIDerivedType *GV 

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

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

PiotrZSL wrote:

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

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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2023-11-08 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

@ChuanqiXu9 Can I use some of your help? This PR breaks two module tests:
```
  Clang :: Modules/cxx20-hu-04.cpp
  Clang :: Modules/cxx20-module-file-info-macros.cpp
```
Apparently I somehow break import or export of header unit macros.

In `cxx20-module-file-info-macros.cpp`, the following part of the test breaks, 
because there are no macro definitions in the output:
https://github.com/llvm/llvm-project/blob/e3c120a585d2740bd1a4de23112fccd82013adbc/clang/test/Modules/cxx20-module-file-info-macros.cpp#L51-L58

In `cxx20-hu-04.cpp`, the following part of the test:
https://github.com/llvm/llvm-project/blob/e3c120a585d2740bd1a4de23112fccd82013adbc/clang/test/Modules/cxx20-hu-04.cpp#L83-L94
produces some unexpected diagnostic:
```
error: 'expected-error' diagnostics expected but not seen:
  File importer-01.cpp Line 9: use of undeclared identifier 'bar'
error: 'expected-error' diagnostics seen but not expected:
  File importer-01.cpp Line 5: use of undeclared identifier 'FORTYTWO'
  File importer-01.cpp Line 9: use of undeclared identifier 'FORTYTWO'
error: 'expected-note' diagnostics expected but not seen:
  File * Line * (directive at importer-01.cpp:10): 'baz' declared here
4 errors generated.
```
which is again a missing macro definition.
Me and Aaron have been trying to debug this, but to no avail.

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


[clang] 8feb083 - [clang][Interp] Consider bit width in IntegralAP::toAPSInt() (#71646)

2023-11-08 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-11-09T07:46:55+01:00
New Revision: 8feb0830cb5c731a34dc74ff6f0c1c4702bc4734

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

LOG: [clang][Interp] Consider bit width in IntegralAP::toAPSInt() (#71646)

In `Interp.h`, when a add/sub/mul fails, we call this code and expect to
get an `APSInt` back that can handle more than the current bitwidth of
the type.

Added: 


Modified: 
clang/lib/AST/Interp/IntegralAP.h
clang/test/AST/Interp/intap.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index b674082d9ea5812..88de1f1392e6813 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -119,8 +119,16 @@ template  class IntegralAP final {
 
   constexpr unsigned bitWidth() const { return V.getBitWidth(); }
 
-  APSInt toAPSInt(unsigned Bits = 0) const { return APSInt(V, !Signed); }
-  APValue toAPValue() const { return APValue(APSInt(V, !Signed)); }
+  APSInt toAPSInt(unsigned Bits = 0) const {
+if (Bits == 0)
+  Bits = bitWidth();
+
+if constexpr (Signed)
+  return APSInt(V.sext(Bits), !Signed);
+else
+  return APSInt(V.zext(Bits), !Signed);
+  }
+  APValue toAPValue() const { return APValue(toAPSInt()); }
 
   bool isZero() const { return V.isZero(); }
   bool isPositive() const { return V.isNonNegative(); }

diff  --git a/clang/test/AST/Interp/intap.cpp b/clang/test/AST/Interp/intap.cpp
index 5f08b76a565c25a..34c8d0565082994 100644
--- a/clang/test/AST/Interp/intap.cpp
+++ b/clang/test/AST/Interp/intap.cpp
@@ -63,11 +63,16 @@ namespace i128 {
 
   static const __int128_t INT128_MAX = UINT128_MAX >> (__int128_t)1;
   static_assert(INT128_MAX != 0, "");
+  static_assert(INT128_MAX == 0, ""); // expected-error {{failed}} \
+  // expected-note {{evaluates to 
'170141183460469231731687303715884105727 == 0'}} \
+  // ref-error {{failed}} \
+  // ref-note {{evaluates to 
'170141183460469231731687303715884105727 == 0'}}
+
   static const __int128_t INT128_MIN = -INT128_MAX - 1;
   constexpr __int128 A = INT128_MAX + 1; // expected-error {{must be 
initialized by a constant expression}} \
- // expected-note {{outside the 
range}} \
+ // expected-note {{value 
170141183460469231731687303715884105728 is outside the range}} \
  // ref-error {{must be initialized by 
a constant expression}} \
- // ref-note {{outside the range}}
+ // ref-note {{value 
170141183460469231731687303715884105728 is outside the range}}
   constexpr int128_t Two = (int128_t)1 << 1ul;
   static_assert(Two == 2, "");
   static_assert(Two, "");



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


[clang] [clang][Interp] Consider bit width in IntegralAP::toAPSInt() (PR #71646)

2023-11-08 Thread Timm Baeder via cfe-commits

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


[clang] b7b5907 - [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (#71014)

2023-11-08 Thread via cfe-commits

Author: Chuanqi Xu
Date: 2023-11-09T14:42:07+08:00
New Revision: b7b5907b56e98719b1dba8364ebcfb264fc09bfe

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

LOG: [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (#71014)

Close https://github.com/llvm/llvm-project/issues/56980.

This patch tries to introduce a light-weight optimization attribute for
coroutines which are guaranteed to only be destroyed after it reached
the final suspend.

The rationale behind the patch is simple. See the example:

```C++
A foo() {
  dtor d;
  co_await something();
  dtor d1;
  co_await something();
  dtor d2;
  co_return 43;
}
```

Generally the generated .destroy function may be:

```C++
void foo.destroy(foo.Frame *frame) {
  switch(frame->suspend_index()) {
case 1:
  frame->d.~dtor();
  break;
case 2:
  frame->d.~dtor();
  frame->d1.~dtor();
  break;
case 3:
  frame->d.~dtor();
  frame->d1.~dtor();
  frame->d2.~dtor();
  break;
default: // coroutine completed or haven't started
  break;
  }

  frame->promise.~promise_type();
  delete frame;
}
```

Since the compiler need to be ready for all the cases that the coroutine
may be destroyed in a valid state.

However, from the user's perspective, we can understand that certain
coroutine types may only be destroyed after it reached to the final
suspend point. And we need a method to teach the compiler about this.
Then this is the patch. After the compiler recognized that the
coroutines can only be destroyed after complete, it can optimize the
above example to:

```C++
void foo.destroy(foo.Frame *frame) {
  frame->promise.~promise_type();
  delete frame;
}
```

I spent a lot of time experimenting and experiencing this in the
downstream. The numbers are really good. In a real-world coroutine-heavy
workload, the size of the build dir (including .o files) reduces 14%.
And the size of final libraries (excluding the .o files) reduces 8% in
Debug mode and 1% in Release mode.

Added: 
clang/test/CodeGenCoroutines/coro-only-destroy-when-complete.cpp
llvm/test/Transforms/Coroutines/coro-only-destroy-when-complete.ll

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/lib/CodeGen/CGCoroutine.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test
llvm/docs/Coroutines.rst
llvm/include/llvm/Bitcode/LLVMBitCodes.h
llvm/include/llvm/IR/Attributes.td
llvm/include/llvm/IR/Function.h
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
llvm/lib/Transforms/Coroutines/CoroSplit.cpp
llvm/lib/Transforms/Utils/CodeExtractor.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8bac599f88503af..7a131cb520aa600 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -296,6 +296,9 @@ Attribute Changes in Clang
   is ignored, changed from the former incorrect suggestion to move it past
   declaration specifiers. (`#58637 
`_)
 
+- Clang now introduced ``[[clang::coro_only_destroy_when_complete]]`` attribute
+  to reduce the size of the destroy functions for coroutines which are known to
+  be destroyed after having reached the final suspend point.
 
 Improvements to Clang's diagnostics
 ---

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 60b54c155e5..31434565becaec6 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1082,6 +1082,18 @@ def CFConsumed : InheritableParamAttr {
   let Documentation = [RetainBehaviorDocs];
 }
 
+
+// coro_only_destroy_when_complete indicates the coroutines whose return type
+// is marked by coro_only_destroy_when_complete can only be destroyed when the
+// coroutine completes. Then the space for the destroy functions can be saved.
+def CoroOnlyDestroyWhenComplete : InheritableAttr {
+  let Spellings = [Clang<"coro_only_destroy_when_complete">];
+  let Subjects = SubjectList<[CXXRecord]>;
+  let LangOpts = [CPlusPlus];
+  let Documentation = [CoroOnlyDestroyWhenCompleteDocs];
+  let SimpleHandler = 1;
+}
+
 // OSObject-based attributes.
 def OSConsumed : InheritableParamAttr {
   let Spellings = [Clang<"os_consumed">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 05703df2129f612..fa6f6acd0c30e88 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7416,3 +7416,69 @@ that ``p->array`` must have at least ``p->count`` number 
of elements available:
 
   }];
 }
+
+def 

[clang] [llvm] [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (PR #71014)

2023-11-08 Thread Chuanqi Xu via cfe-commits

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


[clang] [llvm] [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (PR #71014)

2023-11-08 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Thanks for reviewing this!

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


[clang] Llvm modules on demand bmi (PR #71773)

2023-11-08 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

This is a little bit far from what I imaged.

There are 2 things in the patch. One is to generate the BMI and the object file 
in one phase (phase here means preprocess, precompile, compile, ...). Another 
is to allow us to generate BMI from a `.cpp` file. (Currently we only do this 
for `.cppm` file or `-x c++-module` file).

The first thing is in my TODO too. But my consideration is more about 
efficiency. Currently, the one phase compilation model (I found the term 
`phase` may be ambiguous in the context) used by cmake is actually compile the 
module source file to a BMI and compile the BMI to an object file.

```
x.cppm -> x.pcm -> x.o
```

But after we introduced thin BMI, it looks inefficient to write the AST twice. 
So it is on my TODO list after we land the thin BMI patch. BTW, I think we 
should do thin in CodeGen action instead of hacking on WrappedASTConsumer.

For the second thing, I am curious that if it is necessary now? Or what will it 
block? I mean, the build systems or the cmake, require to mark the module unit 
ahead of time. Then the build systems will pass `-x c++-module` now for module 
units. Then the suffixes are not a thing for users.

And to me, the current mechanism for `.cppm` (or `-x c++-module`) in the driver 
side works pretty well.  And if we introduce the mechanism to produce BMI for 
`.cpp`, it implies that we need to maintain both paths. It is super embracing 
to me.

> in the AST consumer on the BMI side doing suitable filtering to eliminate the 
> content that is not part of the interface, that is either not needed (or in 
> some cases positively unhelpful to consumers).

I believe we should do this in ASTWriters. Also this should be part of thin BMI.

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


[clang] [Clang][InstrProf] Allow absolute path in fun.list of -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits


@@ -139,9 +139,23 @@ std::optional
 ProfileList::isFileExcluded(StringRef FileName,
 CodeGenOptions::ProfileInstrKind Kind) const {
   StringRef Section = getSectionName(Kind);
-  // Check for "source:="
+
+  // Convert the input file path to its canonical (absolute) form
+  llvm::SmallString<128> CanonicalFileName(FileName);
+  llvm::sys::fs::make_absolute(CanonicalFileName);

xgupta wrote:

I updated the position of that piece of code. 
I could not think properly the test case, added one version which was failing 
previously but passing now with the changes in the source file.
I think the issue with the previous version that that was not working when we 
were mixing the relative and completed paths in q single command line 
invocation. 

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


[clang] [Clang][InstrProf] Allow absolute path in fun.list of -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/67519

>From 8fdc14ad3a3060407800fe2c570a3631d2a6e1cc Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Thu, 19 Oct 2023 18:20:05 +0530
Subject: [PATCH 1/2] [Clang][InstrProf] Allow absolute path in fun.list of
 -fprofile-list=

---
 clang/lib/Basic/ProfileList.cpp | 10 ++
 1 file changed, 10 insertions(+)

diff --git a/clang/lib/Basic/ProfileList.cpp b/clang/lib/Basic/ProfileList.cpp
index 8fa16e2eb069a52..1853a3e34ec35ed 100644
--- a/clang/lib/Basic/ProfileList.cpp
+++ b/clang/lib/Basic/ProfileList.cpp
@@ -139,12 +139,22 @@ std::optional
 ProfileList::isFileExcluded(StringRef FileName,
 CodeGenOptions::ProfileInstrKind Kind) const {
   StringRef Section = getSectionName(Kind);
+  // Convert the input file path to its canonical (absolute) form
+  llvm::SmallString<128> CanonicalFileName(FileName);
+  llvm::sys::fs::make_absolute(CanonicalFileName);
+
   // Check for "source:="
   if (auto V = inSection(Section, "source", FileName))
 return V;
+  if (auto V = inSection(Section, "source", CanonicalFileName))
+return V;
   if (SCL->inSection(Section, "!src", FileName))
 return Forbid;
+  if (SCL->inSection(Section, "!src", CanonicalFileName))
+return Forbid;
   if (SCL->inSection(Section, "src", FileName))
 return Allow;
+  if (SCL->inSection(Section, "src", CanonicalFileName))
+return Allow;
   return std::nullopt;
 }

>From 0300a2f7b0359497cc57f14c9dca802c78249b6d Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Thu, 9 Nov 2023 11:27:40 +0530
Subject: [PATCH 2/2] add testing

---
 clang/lib/Basic/ProfileList.cpp | 15 +++
 clang/test/CodeGen/profile-filter.c |  3 ++-
 2 files changed, 9 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Basic/ProfileList.cpp b/clang/lib/Basic/ProfileList.cpp
index 1853a3e34ec35ed..3dc01096a69e2ef 100644
--- a/clang/lib/Basic/ProfileList.cpp
+++ b/clang/lib/Basic/ProfileList.cpp
@@ -139,21 +139,20 @@ std::optional
 ProfileList::isFileExcluded(StringRef FileName,
 CodeGenOptions::ProfileInstrKind Kind) const {
   StringRef Section = getSectionName(Kind);
-  // Convert the input file path to its canonical (absolute) form
-  llvm::SmallString<128> CanonicalFileName(FileName);
-  llvm::sys::fs::make_absolute(CanonicalFileName);
-
   // Check for "source:="
   if (auto V = inSection(Section, "source", FileName))
 return V;
-  if (auto V = inSection(Section, "source", CanonicalFileName))
-return V;
   if (SCL->inSection(Section, "!src", FileName))
 return Forbid;
-  if (SCL->inSection(Section, "!src", CanonicalFileName))
-return Forbid;
   if (SCL->inSection(Section, "src", FileName))
 return Allow;
+  // Convert the input file path to its canonical (absolute) form
+  llvm::SmallString<128> CanonicalFileName(FileName);
+  llvm::sys::fs::make_absolute(CanonicalFileName);
+  if (auto V = inSection(Section, "source", CanonicalFileName))
+return V;
+  if (SCL->inSection(Section, "!src", CanonicalFileName))
+return Forbid;
   if (SCL->inSection(Section, "src", CanonicalFileName))
 return Allow;
   return std::nullopt;
diff --git a/clang/test/CodeGen/profile-filter.c 
b/clang/test/CodeGen/profile-filter.c
index e33e4a0a60b3d4f..2db9d5059e4ccea 100644
--- a/clang/test/CodeGen/profile-filter.c
+++ b/clang/test/CodeGen/profile-filter.c
@@ -4,7 +4,8 @@
 // RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fprofile-list=%t-func.list -emit-llvm %s -o - | 
FileCheck %s --check-prefix=FUNC
 
 // RUN: echo "src:%s" | sed -e 's/\\//g' > %t-file.list
-// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fprofile-list=%t-file.list -emit-llvm %s -o - | 
FileCheck %s --check-prefix=FILE
+// RUN: cd %S
+// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fprofile-list=%t-file.list -emit-llvm profile-filter.c 
-o - | FileCheck %s --check-prefix=FILE
 
 // RUN: echo -e "[clang]\nfun:test1\n[llvm]\nfun:test2" > %t-section.list
 // RUN: %clang_cc1 -fprofile-instrument=llvm -fprofile-list=%t-section.list 
-emit-llvm %s -o - | FileCheck %s --check-prefix=SECTION

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


[clang] [Clang][InstrProf] Allow absolute path in fun.list of -fprofile-list= (PR #67519)

2023-11-08 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/67519

>From 400c889a4f0e867e3e2ceee43ae5c91f62f63c4d Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Thu, 19 Oct 2023 18:20:05 +0530
Subject: [PATCH 1/2] [Clang][InstrProf] Allow absolute path in fun.list of
 -fprofile-list=

---
 clang/lib/Basic/ProfileList.cpp | 10 ++
 1 file changed, 10 insertions(+)

diff --git a/clang/lib/Basic/ProfileList.cpp b/clang/lib/Basic/ProfileList.cpp
index 8fa16e2eb069a52..1853a3e34ec35ed 100644
--- a/clang/lib/Basic/ProfileList.cpp
+++ b/clang/lib/Basic/ProfileList.cpp
@@ -139,12 +139,22 @@ std::optional
 ProfileList::isFileExcluded(StringRef FileName,
 CodeGenOptions::ProfileInstrKind Kind) const {
   StringRef Section = getSectionName(Kind);
+  // Convert the input file path to its canonical (absolute) form
+  llvm::SmallString<128> CanonicalFileName(FileName);
+  llvm::sys::fs::make_absolute(CanonicalFileName);
+
   // Check for "source:="
   if (auto V = inSection(Section, "source", FileName))
 return V;
+  if (auto V = inSection(Section, "source", CanonicalFileName))
+return V;
   if (SCL->inSection(Section, "!src", FileName))
 return Forbid;
+  if (SCL->inSection(Section, "!src", CanonicalFileName))
+return Forbid;
   if (SCL->inSection(Section, "src", FileName))
 return Allow;
+  if (SCL->inSection(Section, "src", CanonicalFileName))
+return Allow;
   return std::nullopt;
 }

>From 42416cdec2e9675fc3d2dfafffcd3b7cf858cc4f Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Thu, 9 Nov 2023 11:27:40 +0530
Subject: [PATCH 2/2] add testing

---
 clang/lib/Basic/ProfileList.cpp | 15 +++
 clang/test/CodeGen/profile-filter.c |  3 ++-
 2 files changed, 9 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Basic/ProfileList.cpp b/clang/lib/Basic/ProfileList.cpp
index 1853a3e34ec35ed..3dc01096a69e2ef 100644
--- a/clang/lib/Basic/ProfileList.cpp
+++ b/clang/lib/Basic/ProfileList.cpp
@@ -139,21 +139,20 @@ std::optional
 ProfileList::isFileExcluded(StringRef FileName,
 CodeGenOptions::ProfileInstrKind Kind) const {
   StringRef Section = getSectionName(Kind);
-  // Convert the input file path to its canonical (absolute) form
-  llvm::SmallString<128> CanonicalFileName(FileName);
-  llvm::sys::fs::make_absolute(CanonicalFileName);
-
   // Check for "source:="
   if (auto V = inSection(Section, "source", FileName))
 return V;
-  if (auto V = inSection(Section, "source", CanonicalFileName))
-return V;
   if (SCL->inSection(Section, "!src", FileName))
 return Forbid;
-  if (SCL->inSection(Section, "!src", CanonicalFileName))
-return Forbid;
   if (SCL->inSection(Section, "src", FileName))
 return Allow;
+  // Convert the input file path to its canonical (absolute) form
+  llvm::SmallString<128> CanonicalFileName(FileName);
+  llvm::sys::fs::make_absolute(CanonicalFileName);
+  if (auto V = inSection(Section, "source", CanonicalFileName))
+return V;
+  if (SCL->inSection(Section, "!src", CanonicalFileName))
+return Forbid;
   if (SCL->inSection(Section, "src", CanonicalFileName))
 return Allow;
   return std::nullopt;
diff --git a/clang/test/CodeGen/profile-filter.c 
b/clang/test/CodeGen/profile-filter.c
index e33e4a0a60b3d4f..2db9d5059e4ccea 100644
--- a/clang/test/CodeGen/profile-filter.c
+++ b/clang/test/CodeGen/profile-filter.c
@@ -4,7 +4,8 @@
 // RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fprofile-list=%t-func.list -emit-llvm %s -o - | 
FileCheck %s --check-prefix=FUNC
 
 // RUN: echo "src:%s" | sed -e 's/\\//g' > %t-file.list
-// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fprofile-list=%t-file.list -emit-llvm %s -o - | 
FileCheck %s --check-prefix=FILE
+// RUN: cd %S
+// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -fprofile-list=%t-file.list -emit-llvm profile-filter.c 
-o - | FileCheck %s --check-prefix=FILE
 
 // RUN: echo -e "[clang]\nfun:test1\n[llvm]\nfun:test2" > %t-section.list
 // RUN: %clang_cc1 -fprofile-instrument=llvm -fprofile-list=%t-section.list 
-emit-llvm %s -o - | FileCheck %s --check-prefix=SECTION

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


[clang] Llvm modules on demand bmi (PR #71773)

2023-11-08 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 21861991e760e7e845dc1be5b804c950543d699a 
6fa533ecaef0f75c87554fb646b0e5dca8ea7255 -- 
clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h 
clang/include/clang/Sema/Sema.h clang/include/clang/Serialization/ASTWriter.h 
clang/include/clang/Serialization/PCHContainerOperations.h 
clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp 
clang/lib/Frontend/FrontendAction.cpp clang/lib/Serialization/GeneratePCH.cpp 
clang/lib/Serialization/PCHContainerOperations.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index bfe112ff1..f6794a4f4 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -197,15 +197,16 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
,
   // to consider the case in which a BMI is explicitly the main output of the
   // compilation.
   InputKind IK = getCurrentFileKind();
-  bool EmitBMI = CI.getLangOpts().CPlusPlusModules &&
- IK.getFormat() == InputKind::Format::Source &&
- !this->usesPreprocessorOnly() &&
-(CI.getFrontendOpts().ProgramAction == frontend::EmitObj ||
- CI.getFrontendOpts().ProgramAction == frontend::EmitAssembly 
||
- CI.getFrontendOpts().ProgramAction == frontend::EmitBC ||
- CI.getFrontendOpts().ProgramAction == frontend::EmitLLVM ||
- CI.getFrontendOpts().ProgramAction == frontend::EmitLLVMOnly 
||
- CI.getFrontendOpts().ProgramAction == 
frontend::EmitCodeGenOnly);
+  bool EmitBMI =
+  CI.getLangOpts().CPlusPlusModules &&
+  IK.getFormat() == InputKind::Format::Source &&
+  !this->usesPreprocessorOnly() &&
+  (CI.getFrontendOpts().ProgramAction == frontend::EmitObj ||
+   CI.getFrontendOpts().ProgramAction == frontend::EmitAssembly ||
+   CI.getFrontendOpts().ProgramAction == frontend::EmitBC ||
+   CI.getFrontendOpts().ProgramAction == frontend::EmitLLVM ||
+   CI.getFrontendOpts().ProgramAction == frontend::EmitLLVMOnly ||
+   CI.getFrontendOpts().ProgramAction == frontend::EmitCodeGenOnly);
 
   // If there are no registered plugins and we do not need to emit a BMI, we
   // do not need to wrap the consumer in a MultiplexConsumer.
@@ -225,8 +226,8 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
,
 // statement).  We do not open this on the output stream, but provide it
 // as a fallback.
 // The default here is to output the pcm alongside the main output.
-std::string XOut
-  = llvm::sys::path::parent_path(CI.getFrontendOpts().OutputFile).str();
+std::string XOut =
+llvm::sys::path::parent_path(CI.getFrontendOpts().OutputFile).str();
 std::string XIn = llvm::sys::path::filename(InFile).str();
 if (!XOut.empty()) {
   XOut += llvm::sys::path::get_separator();
@@ -245,19 +246,19 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
,
 // Add a job to build the CMI from the AST.
 // ??? : change the CTOR flags to note that this is a CXX20 module?
 Consumers.push_back(std::make_unique(
-  CI.getPreprocessor(), CI.getModuleCache(), XOut, Sysroot, Buffer,
-  CI.getFrontendOpts().ModuleFileExtensions,
-  /*AllowASTWithErrors=*/false,
-  /*IncludeTimestamps=*/false,
-  /*BuildingImplicitModule=*/false,
-  /*ShouldCacheASTInMemory=*/false,
-  /*IsForBMI=*/true));
+CI.getPreprocessor(), CI.getModuleCache(), XOut, Sysroot, Buffer,
+CI.getFrontendOpts().ModuleFileExtensions,
+/*AllowASTWithErrors=*/false,
+/*IncludeTimestamps=*/false,
+/*BuildingImplicitModule=*/false,
+/*ShouldCacheASTInMemory=*/false,
+/*IsForBMI=*/true));
 
 // This writes the CMI (if one is needed), but does not open the output
 // file unless/until it is required.
-Consumers.push_back(CI.getPCHContainerWriter()
-.CreatePCHDeferredContainerGenerator(
-CI, std::string(InFile), XOut, std::move(OS), Buffer));
+Consumers.push_back(
+CI.getPCHContainerWriter().CreatePCHDeferredContainerGenerator(
+CI, std::string(InFile), XOut, std::move(OS), Buffer));
   }
 
   // Collect the list of plugins that go before the main action (in Consumers)

``




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


[clang] Llvm modules on demand bmi (PR #71773)

2023-11-08 Thread Iain Sandoe via cfe-commits

https://github.com/iains created https://github.com/llvm/llvm-project/pull/71773

Here is a **draft** of the patch series that allows for emitting both an object 
and a BMI from the same compiler invocation.

Because of point 1) below it's fairly limited in the command lines supported, 
you can do things like:

` clang++  -std=c++20 foo.cpp -c -fmodule-file=X=some/dir/X,pcm `
which will generate `foo.o` in the `CWD` and `X.pcm`  in `CWD/some/dir`

Note that, like GCC's impl you no longer need to have a special name for module 
files, any C++ suffix should work (actually, I'm not 100% sure if the .cppm 
will work without some driver-side mods)

In terms of the mechanism to do the split, I'd hope it's pretty close.

Where more development will be required:
 1. in the process(es) used for finding the BMI name
 2. in the AST consumer on the BMI side doing suitable filtering to eliminate 
the content that is not part of the interface, that is either not needed (or in 
some cases positively unhelpful to consumers).

However, neither 1 or 2 should prevent this being a first step

I"m interested in feedback on the impl.

@ChuanqiXu9 @dwblaikie @Bigcheese @mathstuf @boris-kolpackov @tahonermann 

>From 0918c5ac02c0452092e457313996da2232fbcdf5 Mon Sep 17 00:00:00 2001
From: Iain Sandoe 
Date: Sat, 29 Jan 2022 16:55:24 +
Subject: [PATCH 1/4] [Modules] A utility to identify compilations that produce
 BMIs.

We want to be able to decide if a given compilation should emit a
BMI if an appropriate module line is found.  We must not confuse
these cases with an implementation that implicitly pulls in its
respective interface.

Differential Revision: https://reviews.llvm.org/D118895
---
 clang/include/clang/Sema/Sema.h | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index a8c41492b61ac4c..44234d982e379f3 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2389,6 +2389,11 @@ class Sema final {
 
   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
 
+  /// Determine if the current module scope is the implementation.
+  bool isModuleImplementation() const {
+return ModuleScopes.empty() ? false : !ModuleScopes.back().ModuleInterface;
+  }
+
   // When loading a non-modular PCH files, this is used to restore module
   // visibility.
   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {

>From ee75fb36b85b29d3bbec9e99c5fa5a1e69137373 Mon Sep 17 00:00:00 2001
From: Iain Sandoe 
Date: Sat, 29 Jan 2022 16:39:01 +
Subject: [PATCH 2/4] [Modules] Allow outputing BMIs in the same job as other
 artefacts.

This provides a base implementation for the ability to emit binary
module interfaces in the same compilation as generating object or
other output.

This part defers opening the BMI PCM file until it is actually needed.
At this point we will have parsed the TU and therefore can determine
if this job should emit both the BMI and some other artefact (in many
cases an object file).

This initial implementation assumes that the output filename for the
potential BMI will be known when the job is created.

Differential Revision: https://reviews.llvm.org/D118896
---
 .../ObjectFilePCHContainerOperations.h|  6 +++
 clang/include/clang/Serialization/ASTWriter.h |  3 +-
 .../Serialization/PCHContainerOperations.h| 16 ++
 .../ObjectFilePCHContainerOperations.cpp  | 10 
 clang/lib/Serialization/GeneratePCH.cpp   | 36 ++---
 .../Serialization/PCHContainerOperations.cpp  | 51 +++
 6 files changed, 115 insertions(+), 7 deletions(-)

diff --git a/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h 
b/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
index 7a02d8725885a48..e09a45d76dd7866 100644
--- a/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
+++ b/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
@@ -27,6 +27,12 @@ class ObjectFilePCHContainerWriter : public 
PCHContainerWriter {
   const std::string ,
   std::unique_ptr OS,
   std::shared_ptr Buffer) const 
override;
+
+  std::unique_ptr CreatePCHDeferredContainerGenerator(
+  CompilerInstance , const std::string ,
+  const std::string ,
+  std::unique_ptr OS,
+  std::shared_ptr Buffer) const override;
 };
 
 /// A PCHContainerReader implementation that uses LLVM to
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 3019bbc2ddc9cc7..3dc3d00b9eafca9 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -807,6 +807,7 @@ class PCHGenerator : public SemaConsumer {
   ASTWriter Writer;
   bool AllowASTWithErrors;
   bool ShouldCacheASTInMemory;
+  bool IsForBMI;
 
 protected:
   ASTWriter () { return Writer; }
@@ -820,7 

[clang] Fix clang to recognize new C23 modifiers %w and %wf when printing (PR #71771)

2023-11-08 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 21861991e760e7e845dc1be5b804c950543d699a 
06c4cf02dfb4b20c8349c5f3c7209276f6d56edf -- 
clang/include/clang/AST/FormatString.h clang/lib/AST/FormatString.cpp 
clang/lib/AST/PrintfFormatString.cpp clang/test/Sema/format-strings-ms.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 6a886854650f..8272f65dffcd 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -81,9 +81,10 @@ public:
 AsLongDouble, // 'L'
 AsAllocate,   // for '%as', GNU extension to C90 scanf
 AsMAllocate,  // for '%ms', GNU extension to scanf
-AsWide,   // 'w' (1. MSVCRT, like l but only for c, C, s, S, or Z on 
windows
-  // 2. for b, d, i, o, u, x, or X when a size followed(like 
8, 16, 32 or 64)
-AsWideFast,   // 'wf' (for b, d, i, o, u, x, or X)
+AsWide, // 'w' (1. MSVCRT, like l but only for c, C, s, S, or Z on windows
+// 2. for b, d, i, o, u, x, or X when a size followed(like 8, 16, 
32
+// or 64)
+AsWideFast,  // 'wf' (for b, d, i, o, u, x, or X)
 AsWideChar = AsLong, // for '%ls', only makes sense for printf
   };
 
@@ -420,6 +421,7 @@ protected:
   bool UsesPositionalArg;
   unsigned argIndex;
   unsigned size;
+
 public:
   FormatSpecifier(bool isPrintf)
 : CS(isPrintf), VectorNumElts(false),
@@ -463,14 +465,9 @@ public:
 FieldWidth = Amt;
   }
 
-  void setSize(unsigned s) {
-size = s;
-  }
-
-  unsigned getSize() const {
-return size;
-  }
+  void setSize(unsigned s) { size = s; }
 
+  unsigned getSize() const { return size; }
 
   bool usesPositionalArg() const { return UsesPositionalArg; }
 
diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index ebc136e78071..1f8eacb3dc45 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -287,7 +287,8 @@ 
clang::analyze_format_string::ParseLengthModifier(FormatSpecifier ,
   break;
 case 'w':
   ++I;
-  if (I == E) return false;
+  if (I == E)
+return false;
   if (*I == 'f') {
 lmKind = LengthModifier::AsWideFast;
 ++I;
@@ -295,7 +296,8 @@ 
clang::analyze_format_string::ParseLengthModifier(FormatSpecifier ,
 lmKind = LengthModifier::AsWide;
   }
 
-  if (I == E) return false;
+  if (I == E)
+return false;
   int s = 0;
   while (unsigned(*I - '0') <= 9) {
 s = 10 * s + unsigned(*I - '0');
@@ -303,9 +305,10 @@ 
clang::analyze_format_string::ParseLengthModifier(FormatSpecifier ,
   }
 
   // s == 0 is MSVCRT case, like l but only for c, C, s, S, or Z on windows
-  // s != 0 for b, d, i, o, u, x, or X when a size followed(like 8, 16, 32 
or 64)
+  // s != 0 for b, d, i, o, u, x, or X when a size followed(like 8, 16, 32
+  // or 64)
   if (s != 0) {
-std::set supported_list {8, 16, 32, 64};
+std::set supported_list{8, 16, 32, 64};
 if (supported_list.count(s) == 0) {
   return false;
 }
@@ -1008,19 +1011,19 @@ bool FormatSpecifier::hasValidLengthModifier(const 
TargetInfo ,
   return true;
 default:
   return false;
-  }
+}
 case LengthModifier::AsWideFast:
   switch (CS.getKind()) {
-case ConversionSpecifier::bArg:
-case ConversionSpecifier::dArg:
-case ConversionSpecifier::iArg:
-case ConversionSpecifier::oArg:
-case ConversionSpecifier::uArg:
-case ConversionSpecifier::xArg:
-case ConversionSpecifier::XArg:
-  return true;
-default:
-  return false;
+  case ConversionSpecifier::bArg:
+  case ConversionSpecifier::dArg:
+  case ConversionSpecifier::iArg:
+  case ConversionSpecifier::oArg:
+  case ConversionSpecifier::uArg:
+  case ConversionSpecifier::xArg:
+  case ConversionSpecifier::XArg:
+return true;
+  default:
+return false;
   }
   }
   llvm_unreachable("Invalid LengthModifier Kind!");
diff --git a/clang/lib/AST/PrintfFormatString.cpp 
b/clang/lib/AST/PrintfFormatString.cpp
index 4b9111e8bcf5..56fb6467c894 100644
--- a/clang/lib/AST/PrintfFormatString.cpp
+++ b/clang/lib/AST/PrintfFormatString.cpp
@@ -542,11 +542,17 @@ ArgType PrintfSpecifier::getScalarArgType(ASTContext ,
   case LengthModifier::AsWideFast:
 int s = getSize();
 bool fast = LM.getKind() == LengthModifier::AsWideFast ? true : false;
-ArgType fastType = Ctx.getTargetInfo().getTriple().isArch64Bit() ? 
Ctx.LongLongTy : Ctx.IntTy;
-if (s == 8) return Ctx.CharTy;
-if (s == 16) return fast? fastType : Ctx.ShortTy;
-

[libunwind] MIPS/libunwind: Use -mfp64 if compiler is FPXX (PR #68521)

2023-11-08 Thread YunQiang Su via cfe-commits

wzssyqa wrote:

@brad0 can you have a look at this PR?

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


[clang] Fix clang to recognize new C23 modifiers %w and %wf when printing (PR #71771)

2023-11-08 Thread via cfe-commits


@@ -85,4 +86,31 @@ void z_test(void *p) {
   scanf("%Z", p); // expected-warning{{invalid conversion specifier 'Z'}}
 }
 
+void w_int_test(void) {

ZijunZhaoCCK wrote:

1. I can't find any tests to verify the print result is correct. Do I miss 
something?
2. One more test about error handling: `unsupported size` test is missing. Like 
`printf("%w20d")` should be thrown or raise errors. Should I raise error or any 
methods to throw the error?

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


[clang] Clang/MIPS: Use -mnan value for -mabs if not specified (PR #71157)

2023-11-08 Thread YunQiang Su via cfe-commits

wzssyqa wrote:

@brad0 can you have a look at this?

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


[clang] Fix clang to recognize new C23 modifiers %w and %wf when printing (PR #71771)

2023-11-08 Thread via cfe-commits

https://github.com/ZijunZhaoCCK created 
https://github.com/llvm/llvm-project/pull/71771

None

>From 06c4cf02dfb4b20c8349c5f3c7209276f6d56edf Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Thu, 9 Nov 2023 02:21:46 +
Subject: [PATCH] Fix clang to recognize new C23 modifiers %w and %wf when
 printing

---
 clang/include/clang/AST/FormatString.h | 16 +++-
 clang/lib/AST/FormatString.cpp | 52 +-
 clang/lib/AST/PrintfFormatString.cpp   | 19 ++
 clang/test/Sema/format-strings-ms.c| 28 ++
 4 files changed, 112 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 5c4ad9baaef608c..6a886854650f1d9 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -81,8 +81,10 @@ class LengthModifier {
 AsLongDouble, // 'L'
 AsAllocate,   // for '%as', GNU extension to C90 scanf
 AsMAllocate,  // for '%ms', GNU extension to scanf
-AsWide,   // 'w' (MSVCRT, like l but only for c, C, s, S, or Z
-AsWideChar = AsLong // for '%ls', only makes sense for printf
+AsWide,   // 'w' (1. MSVCRT, like l but only for c, C, s, S, or Z on 
windows
+  // 2. for b, d, i, o, u, x, or X when a size followed(like 
8, 16, 32 or 64)
+AsWideFast,   // 'wf' (for b, d, i, o, u, x, or X)
+AsWideChar = AsLong, // for '%ls', only makes sense for printf
   };
 
   LengthModifier()
@@ -417,6 +419,7 @@ class FormatSpecifier {
   ///  http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
   bool UsesPositionalArg;
   unsigned argIndex;
+  unsigned size;
 public:
   FormatSpecifier(bool isPrintf)
 : CS(isPrintf), VectorNumElts(false),
@@ -460,6 +463,15 @@ class FormatSpecifier {
 FieldWidth = Amt;
   }
 
+  void setSize(unsigned s) {
+size = s;
+  }
+
+  unsigned getSize() const {
+return size;
+  }
+
+
   bool usesPositionalArg() const { return UsesPositionalArg; }
 
   bool hasValidLengthModifier(const TargetInfo ,
diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index e0c9e18cfe3a243..ebc136e780717e4 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -286,7 +286,33 @@ 
clang::analyze_format_string::ParseLengthModifier(FormatSpecifier ,
   lmKind = LengthModifier::AsInt3264;
   break;
 case 'w':
-  lmKind = LengthModifier::AsWide; ++I; break;
+  ++I;
+  if (I == E) return false;
+  if (*I == 'f') {
+lmKind = LengthModifier::AsWideFast;
+++I;
+  } else {
+lmKind = LengthModifier::AsWide;
+  }
+
+  if (I == E) return false;
+  int s = 0;
+  while (unsigned(*I - '0') <= 9) {
+s = 10 * s + unsigned(*I - '0');
+++I;
+  }
+
+  // s == 0 is MSVCRT case, like l but only for c, C, s, S, or Z on windows
+  // s != 0 for b, d, i, o, u, x, or X when a size followed(like 8, 16, 32 
or 64)
+  if (s != 0) {
+std::set supported_list {8, 16, 32, 64};
+if (supported_list.count(s) == 0) {
+  return false;
+}
+FS.setSize(s);
+  }
+
+  break;
   }
   LengthModifier lm(lmPosition, lmKind);
   FS.setLengthModifier(lm);
@@ -703,6 +729,8 @@ analyze_format_string::LengthModifier::toString() const {
 return "m";
   case AsWide:
 return "w";
+  case AsWideFast:
+return "wf";
   case None:
 return "";
   }
@@ -970,6 +998,27 @@ bool FormatSpecifier::hasValidLengthModifier(const 
TargetInfo ,
 case ConversionSpecifier::SArg:
 case ConversionSpecifier::ZArg:
   return Target.getTriple().isOSMSVCRT();
+case ConversionSpecifier::bArg:
+case ConversionSpecifier::dArg:
+case ConversionSpecifier::iArg:
+case ConversionSpecifier::oArg:
+case ConversionSpecifier::uArg:
+case ConversionSpecifier::xArg:
+case ConversionSpecifier::XArg:
+  return true;
+default:
+  return false;
+  }
+case LengthModifier::AsWideFast:
+  switch (CS.getKind()) {
+case ConversionSpecifier::bArg:
+case ConversionSpecifier::dArg:
+case ConversionSpecifier::iArg:
+case ConversionSpecifier::oArg:
+case ConversionSpecifier::uArg:
+case ConversionSpecifier::xArg:
+case ConversionSpecifier::XArg:
+  return true;
 default:
   return false;
   }
@@ -996,6 +1045,7 @@ bool FormatSpecifier::hasStandardLengthModifier() const {
 case LengthModifier::AsInt3264:
 case LengthModifier::AsInt64:
 case LengthModifier::AsWide:
+case LengthModifier::AsWideFast:
 case LengthModifier::AsShortLong: // ???
   return false;
   }
diff --git a/clang/lib/AST/PrintfFormatString.cpp 
b/clang/lib/AST/PrintfFormatString.cpp
index f0b9d0ecaf23461..4b9111e8bcf509a 100644
--- a/clang/lib/AST/PrintfFormatString.cpp
+++ 

[openmp] [clang] [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL (PR #71234)

2023-11-08 Thread Saiyedul Islam via cfe-commits

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


[clang] 2186199 - [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL (#71234)

2023-11-08 Thread via cfe-commits

Author: Saiyedul Islam
Date: 2023-11-09T10:34:35+05:30
New Revision: 21861991e760e7e845dc1be5b804c950543d699a

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

LOG: [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL (#71234)

Fixes the DeviceRTL compilation to ensure it is ABI agnostic. Uses
already available global variable "oclc_ABI_version" instead of
"llvm.amdgcn.abi.verion".

It also adds some minor fields in ImplicitArg structure.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/Targets/AMDGPU.cpp
clang/test/CodeGen/amdgpu-abi-version.c
clang/test/CodeGen/amdgpu-address-spaces.cpp
clang/test/CodeGenCUDA/amdgpu-code-object-version-linking.cu
clang/test/CodeGenCUDA/amdgpu-workgroup-size.cu
openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e7e498e8a933131..d49c44dbaace3a8 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17432,11 +17432,11 @@ Value *EmitAMDGPUImplicitArgPtr(CodeGenFunction ) 
{
 /// Emit code based on Code Object ABI version.
 /// COV_4: Emit code to use dispatch ptr
 /// COV_5: Emit code to use implicitarg ptr
-/// COV_NONE : Emit code to load a global variable "llvm.amdgcn.abi.version"
+/// COV_NONE : Emit code to load a global variable "__oclc_ABI_version"
 ///and use its value for COV_4 or COV_5 approach. It is used for
 ///compiling device libraries in an ABI-agnostic way.
 ///
-/// Note: "llvm.amdgcn.abi.version" is supposed to be emitted and intialized by
+/// Note: "__oclc_ABI_version" is supposed to be emitted and intialized by
 ///   clang during compilation of user code.
 Value *EmitAMDGPUWorkGroupSize(CodeGenFunction , unsigned Index) {
   llvm::LoadInst *LD;
@@ -17444,7 +17444,7 @@ Value *EmitAMDGPUWorkGroupSize(CodeGenFunction , 
unsigned Index) {
   auto Cov = CGF.getTarget().getTargetOpts().CodeObjectVersion;
 
   if (Cov == clang::TargetOptions::COV_None) {
-StringRef Name = "llvm.amdgcn.abi.version";
+StringRef Name = "__oclc_ABI_version";
 auto *ABIVersionC = CGF.CGM.getModule().getNamedGlobal(Name);
 if (!ABIVersionC)
   ABIVersionC = new llvm::GlobalVariable(

diff  --git a/clang/lib/CodeGen/Targets/AMDGPU.cpp 
b/clang/lib/CodeGen/Targets/AMDGPU.cpp
index 0411846cf9b02bd..4dd25213dda9fa5 100644
--- a/clang/lib/CodeGen/Targets/AMDGPU.cpp
+++ b/clang/lib/CodeGen/Targets/AMDGPU.cpp
@@ -362,11 +362,15 @@ void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
 /// AMDGPU ROCm device libraries.
 void AMDGPUTargetCodeGenInfo::emitTargetGlobals(
 CodeGen::CodeGenModule ) const {
-  StringRef Name = "llvm.amdgcn.abi.version";
+  StringRef Name = "__oclc_ABI_version";
   llvm::GlobalVariable *OriginalGV = CGM.getModule().getNamedGlobal(Name);
   if (OriginalGV && 
!llvm::GlobalVariable::isExternalLinkage(OriginalGV->getLinkage()))
 return;
 
+  if (CGM.getTarget().getTargetOpts().CodeObjectVersion ==
+  clang::TargetOptions::COV_None)
+return;
+
   auto *Type = llvm::IntegerType::getIntNTy(CGM.getModule().getContext(), 32);
   llvm::Constant *COV = llvm::ConstantInt::get(
   Type, CGM.getTarget().getTargetOpts().CodeObjectVersion);

diff  --git a/clang/test/CodeGen/amdgpu-abi-version.c 
b/clang/test/CodeGen/amdgpu-abi-version.c
index d1189545139e2a6..4e5ad87655f2305 100644
--- a/clang/test/CodeGen/amdgpu-abi-version.c
+++ b/clang/test/CodeGen/amdgpu-abi-version.c
@@ -2,14 +2,14 @@
 // RUN: %clang_cc1 -cc1 -triple amdgcn-amd-amdhsa -emit-llvm 
-mcode-object-version=none %s -o - | FileCheck %s
 
 //.
-// CHECK: @llvm.amdgcn.abi.version = weak_odr hidden local_unnamed_addr 
addrspace(4) constant i32 0
+// CHECK: @__oclc_ABI_version = external addrspace(4) global i32
 //.
 // CHECK-LABEL: define dso_local i32 @foo(
 // CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[RETVAL:%.*]] = alloca i32, align 4, addrspace(5)
 // CHECK-NEXT:[[RETVAL_ASCAST:%.*]] = addrspacecast ptr addrspace(5) 
[[RETVAL]] to ptr
-// CHECK-NEXT:[[TMP0:%.*]] = load i32, ptr addrspace(4) 
@llvm.amdgcn.abi.version, align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, ptr addrspace(4) 
@__oclc_ABI_version, align 4
 // CHECK-NEXT:[[TMP1:%.*]] = icmp sge i32 [[TMP0]], 500
 // CHECK-NEXT:[[TMP2:%.*]] = call align 8 dereferenceable(256) ptr 
addrspace(4) @llvm.amdgcn.implicitarg.ptr()
 // CHECK-NEXT:[[TMP3:%.*]] = getelementptr i8, ptr addrspace(4) [[TMP2]], 
i32 12

diff  --git a/clang/test/CodeGen/amdgpu-address-spaces.cpp 
b/clang/test/CodeGen/amdgpu-address-spaces.cpp
index a9994881eb06228..0a808aa6cc75ed3 100644
--- a/clang/test/CodeGen/amdgpu-address-spaces.cpp
+++ 

[openmp] [clang] [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL (PR #71234)

2023-11-08 Thread Saiyedul Islam via cfe-commits

https://github.com/saiislam updated 
https://github.com/llvm/llvm-project/pull/71234

>From a6627248612fd2ab577b456a791e08164674efcc Mon Sep 17 00:00:00 2001
From: Saiyedul Islam 
Date: Fri, 3 Nov 2023 16:16:25 -0500
Subject: [PATCH 1/3] [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL

Fixes the DeviceRTL compilation to ensure it is ABI agnostic.
Uses already available global variable "oclc_ABI_version" instead
of "llvm.amdgcn.abi.verion".

It also adds some minor fields in ImplicitArg structure.
---
 clang/include/clang/Basic/TargetOptions.h |  2 +-
 clang/lib/CodeGen/CGBuiltin.cpp   |  6 +-
 clang/lib/CodeGen/Targets/AMDGPU.cpp  |  5 +-
 clang/test/CodeGen/amdgpu-abi-version.c   |  4 +-
 clang/test/CodeGen/amdgpu-address-spaces.cpp  |  2 +-
 .../amdgpu-code-object-version-linking.cu | 16 +++---
 .../test/CodeGenCUDA/amdgpu-workgroup-size.cu |  6 +-
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 57 +++
 .../amdgpu/utils/UtilitiesRTL.h   |  4 +-
 9 files changed, 82 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/Basic/TargetOptions.h 
b/clang/include/clang/Basic/TargetOptions.h
index ba3acd029587160..7497e580d27338d 100644
--- a/clang/include/clang/Basic/TargetOptions.h
+++ b/clang/include/clang/Basic/TargetOptions.h
@@ -88,7 +88,7 @@ class TargetOptions {
 COV_5 = 500,
   };
   /// \brief Code object version for AMDGPU.
-  CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_None;
+  CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_4;
 
   /// \brief Enumeration values for AMDGPU printf lowering scheme
   enum class AMDGPUPrintfKind {
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e7e498e8a933131..d49c44dbaace3a8 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17432,11 +17432,11 @@ Value *EmitAMDGPUImplicitArgPtr(CodeGenFunction ) 
{
 /// Emit code based on Code Object ABI version.
 /// COV_4: Emit code to use dispatch ptr
 /// COV_5: Emit code to use implicitarg ptr
-/// COV_NONE : Emit code to load a global variable "llvm.amdgcn.abi.version"
+/// COV_NONE : Emit code to load a global variable "__oclc_ABI_version"
 ///and use its value for COV_4 or COV_5 approach. It is used for
 ///compiling device libraries in an ABI-agnostic way.
 ///
-/// Note: "llvm.amdgcn.abi.version" is supposed to be emitted and intialized by
+/// Note: "__oclc_ABI_version" is supposed to be emitted and intialized by
 ///   clang during compilation of user code.
 Value *EmitAMDGPUWorkGroupSize(CodeGenFunction , unsigned Index) {
   llvm::LoadInst *LD;
@@ -17444,7 +17444,7 @@ Value *EmitAMDGPUWorkGroupSize(CodeGenFunction , 
unsigned Index) {
   auto Cov = CGF.getTarget().getTargetOpts().CodeObjectVersion;
 
   if (Cov == clang::TargetOptions::COV_None) {
-StringRef Name = "llvm.amdgcn.abi.version";
+StringRef Name = "__oclc_ABI_version";
 auto *ABIVersionC = CGF.CGM.getModule().getNamedGlobal(Name);
 if (!ABIVersionC)
   ABIVersionC = new llvm::GlobalVariable(
diff --git a/clang/lib/CodeGen/Targets/AMDGPU.cpp 
b/clang/lib/CodeGen/Targets/AMDGPU.cpp
index 0411846cf9b02bd..d793d27e0db8b80 100644
--- a/clang/lib/CodeGen/Targets/AMDGPU.cpp
+++ b/clang/lib/CodeGen/Targets/AMDGPU.cpp
@@ -362,11 +362,14 @@ void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
 /// AMDGPU ROCm device libraries.
 void AMDGPUTargetCodeGenInfo::emitTargetGlobals(
 CodeGen::CodeGenModule ) const {
-  StringRef Name = "llvm.amdgcn.abi.version";
+  StringRef Name = "__oclc_ABI_version";
   llvm::GlobalVariable *OriginalGV = CGM.getModule().getNamedGlobal(Name);
   if (OriginalGV && 
!llvm::GlobalVariable::isExternalLinkage(OriginalGV->getLinkage()))
 return;
 
+  if(CGM.getTarget().getTargetOpts().CodeObjectVersion == 
clang::TargetOptions::COV_None)
+return;
+
   auto *Type = llvm::IntegerType::getIntNTy(CGM.getModule().getContext(), 32);
   llvm::Constant *COV = llvm::ConstantInt::get(
   Type, CGM.getTarget().getTargetOpts().CodeObjectVersion);
diff --git a/clang/test/CodeGen/amdgpu-abi-version.c 
b/clang/test/CodeGen/amdgpu-abi-version.c
index d1189545139e2a6..4e5ad87655f2305 100644
--- a/clang/test/CodeGen/amdgpu-abi-version.c
+++ b/clang/test/CodeGen/amdgpu-abi-version.c
@@ -2,14 +2,14 @@
 // RUN: %clang_cc1 -cc1 -triple amdgcn-amd-amdhsa -emit-llvm 
-mcode-object-version=none %s -o - | FileCheck %s
 
 //.
-// CHECK: @llvm.amdgcn.abi.version = weak_odr hidden local_unnamed_addr 
addrspace(4) constant i32 0
+// CHECK: @__oclc_ABI_version = external addrspace(4) global i32
 //.
 // CHECK-LABEL: define dso_local i32 @foo(
 // CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[RETVAL:%.*]] = alloca i32, align 4, addrspace(5)
 // CHECK-NEXT:[[RETVAL_ASCAST:%.*]] = addrspacecast ptr addrspace(5) 
[[RETVAL]] to ptr
-// CHECK-NEXT:[[TMP0:%.*]] = load 

[clang] [llvm] [clang-tools-extra] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Bill Wendling via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());
+  CharUnits Size = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  llvm::Constant *ElemSize =
+  llvm::ConstantInt::get(CountedByInst->getType(), Size.getQuantity());
+
+  llvm::Value *FAMSize = Builder.CreateMul(CountedByInst, ElemSize);

bwendling wrote:

However, yes it seems like I'll have to ensure that we're not pointing outside 
of the struct here.

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


[clang] [clang-tools-extra] [llvm] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Bill Wendling via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());
+  CharUnits Size = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  llvm::Constant *ElemSize =
+  llvm::ConstantInt::get(CountedByInst->getType(), Size.getQuantity());
+
+  llvm::Value *FAMSize = Builder.CreateMul(CountedByInst, ElemSize);

bwendling wrote:

I think you need to use pointers here. See https://godbolt.org/z/qWjs4TeW6

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


[clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71755)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/71755

>From 17921d5a1d74017128691428815ede53ac1a4d67 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 8 Nov 2023 17:55:56 -0800
Subject: [PATCH] [clang-format] Handle variable declarations in
 BreakAfterAttributes

Also cleaned up some old test cases.

Fixes #71563.
---
 clang/docs/ClangFormatStyleOptions.rst | 13 +++--
 clang/include/clang/Format/Format.h| 13 +++--
 clang/lib/Format/TokenAnnotator.cpp| 22 +--
 clang/unittests/Format/FormatTest.cpp  | 38 ++
 4 files changed, 62 insertions(+), 24 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 21342e1b89ea866..d496fc85f7ae71a 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,8 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a function
-  declaration/definition name.
+  Break after a group of C++11 attributes before a variable/function
+  (including constructor/destructor) declaration/definition name.
 
   Possible values:
 
@@ -2059,6 +2059,10 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]]
+  const int i;
+  [[gnu::const]] [[maybe_unused]]
+  int j;
   [[nodiscard]]
   inline int f();
   [[gnu::const]] [[nodiscard]]
@@ -2069,6 +2073,9 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]] const int i;
+  [[gnu::const]] [[maybe_unused]]
+  int j;
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
@@ -2078,6 +2085,8 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]] const int i;
+  [[gnu::const]] [[maybe_unused]] int j;
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]] int g();
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3e9d1915badd87f..9442344000e142b 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1428,6 +1428,10 @@ struct FormatStyle {
   enum AttributeBreakingStyle : int8_t {
 /// Always break after attributes.
 /// \code
+///   [[maybe_unused]]
+///   const int i;
+///   [[gnu::const]] [[maybe_unused]]
+///   int j;
 ///   [[nodiscard]]
 ///   inline int f();
 ///   [[gnu::const]] [[nodiscard]]
@@ -1436,6 +1440,9 @@ struct FormatStyle {
 ABS_Always,
 /// Leave the line breaking after attributes as is.
 /// \code
+///   [[maybe_unused]] const int i;
+///   [[gnu::const]] [[maybe_unused]]
+///   int j;
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
@@ -1443,14 +1450,16 @@ struct FormatStyle {
 ABS_Leave,
 /// Never break after attributes.
 /// \code
+///   [[maybe_unused]] const int i;
+///   [[gnu::const]] [[maybe_unused]] int j;
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]] int g();
 /// \endcode
 ABS_Never,
   };
 
-  /// Break after a group of C++11 attributes before a function
-  /// declaration/definition name.
+  /// Break after a group of C++11 attributes before a variable/function
+  /// (including constructor/destructor) declaration/definition name.
   /// \version 16
   AttributeBreakingStyle BreakAfterAttributes;
 
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 729e7e370bf62ea..12f2e2ded19a01c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2000,6 +2000,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = 
   Current.setType(TT_StartOfName);
+  if (auto *PrevNonComment = Current.getPreviousNonComment();
+  PrevNonComment && PrevNonComment->is(TT_StartOfName)) {
+PrevNonComment->setType(TT_Unknown);
+  }
 } else if (Current.is(tok::semi)) {
   // Reset FirstStartOfName after finding a semicolon so that a for loop
   // with multiple increment statements is not confused with a for loop
@@ -3258,7 +3262,7 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   if (Current.is(TT_FunctionDeclarationName))
 return true;
 
-  if (!Current.Tok.getIdentifierInfo())
+  if (!Current.Tok.getIdentifierInfo() || Current.is(TT_CtorDtorDeclName))
 return false;
 
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
@@ -3441,19 +3445,19 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
   if 

[clang] 1f21e49 - Revert "Revert "[AMDGPU] const-fold imm operands of (#71669)

2023-11-08 Thread via cfe-commits

Author: Pravin Jagtap
Date: 2023-11-09T10:09:22+05:30
New Revision: 1f21e49870feebe6971be4db8d32eee646368cc4

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

LOG: Revert "Revert "[AMDGPU] const-fold imm operands of (#71669)

amdgcn_update_dpp intrinsic (#71139)""

This reverts commit d1fb9307951319eea3e869d78470341d603c8363 and fixes
the lit test clang/test/CodeGenHIP/dpp-const-fold.hip

-

Authored-by: Pravin Jagtap 

Added: 
clang/test/CodeGenHIP/dpp-const-fold.hip

Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenFunction.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 5ab81cc605819c3..e7e498e8a933131 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -5708,18 +5708,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 llvm::FunctionType *FTy = F->getFunctionType();
 
 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
-  Value *ArgValue;
-  // If this is a normal argument, just emit it as a scalar.
-  if ((ICEArguments & (1 << i)) == 0) {
-ArgValue = EmitScalarExpr(E->getArg(i));
-  } else {
-// If this is required to be a constant, constant fold it so that we
-// know that the generated intrinsic gets a ConstantInt.
-ArgValue = llvm::ConstantInt::get(
-getLLVMContext(),
-*E->getArg(i)->getIntegerConstantExpr(getContext()));
-  }
-
+  Value *ArgValue = EmitScalarOrConstFoldImmArg(ICEArguments, i, E);
   // If the intrinsic arg type is 
diff erent from the builtin arg type
   // we need to do a bit cast.
   llvm::Type *PTy = FTy->getParamType(i);
@@ -8599,15 +8588,7 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned 
BuiltinID,
   }
 }
 
-if ((ICEArguments & (1 << i)) == 0) {
-  Ops.push_back(EmitScalarExpr(E->getArg(i)));
-} else {
-  // If this is required to be a constant, constant fold it so that we know
-  // that the generated intrinsic gets a ConstantInt.
-  Ops.push_back(llvm::ConstantInt::get(
-  getLLVMContext(),
-  *E->getArg(i)->getIntegerConstantExpr(getContext(;
-}
+Ops.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, i, E));
   }
 
   switch (BuiltinID) {
@@ -11094,15 +11075,7 @@ Value 
*CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID,
 continue;
   }
 }
-if ((ICEArguments & (1 << i)) == 0) {
-  Ops.push_back(EmitScalarExpr(E->getArg(i)));
-} else {
-  // If this is required to be a constant, constant fold it so that we know
-  // that the generated intrinsic gets a ConstantInt.
-  Ops.push_back(llvm::ConstantInt::get(
-  getLLVMContext(),
-  *E->getArg(i)->getIntegerConstantExpr(getContext(;
-}
+Ops.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, i, E));
   }
 
   auto SISDMap = ArrayRef(AArch64SISDIntrinsicMap);
@@ -13814,16 +13787,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
   assert(Error == ASTContext::GE_None && "Should not codegen an error");
 
   for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) {
-// If this is a normal argument, just emit it as a scalar.
-if ((ICEArguments & (1 << i)) == 0) {
-  Ops.push_back(EmitScalarExpr(E->getArg(i)));
-  continue;
-}
-
-// If this is required to be a constant, constant fold it so that we know
-// that the generated intrinsic gets a ConstantInt.
-Ops.push_back(llvm::ConstantInt::get(
-getLLVMContext(), 
*E->getArg(i)->getIntegerConstantExpr(getContext(;
+Ops.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, i, E));
   }
 
   // These exist so that the builtin that takes an immediate can be bounds
@@ -17588,6 +17552,23 @@ void CodeGenFunction::ProcessOrderScopeAMDGCN(Value 
*Order, Value *Scope,
   SSID = getLLVMContext().getOrInsertSyncScopeID(scp);
 }
 
+llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned 
ICEArguments,
+  unsigned Idx,
+  const CallExpr *E) {
+  llvm::Value *Arg = nullptr;
+  if ((ICEArguments & (1 << Idx)) == 0) {
+Arg = EmitScalarExpr(E->getArg(Idx));
+  } else {
+// If this is required to be a constant, constant fold it so that we
+// know that the generated intrinsic gets a ConstantInt.
+std::optional Result =
+E->getArg(Idx)->getIntegerConstantExpr(getContext());
+assert(Result && "Expected argument to be a constant");
+Arg = llvm::ConstantInt::get(getLLVMContext(), *Result);
+  }
+  return Arg;
+}
+
 Value 

[clang] Revert "Revert "[AMDGPU] const-fold imm operands of (PR #71669)

2023-11-08 Thread Pravin Jagtap via cfe-commits

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


[clang] [openmp] [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL (PR #71234)

2023-11-08 Thread Saiyedul Islam via cfe-commits

https://github.com/saiislam updated 
https://github.com/llvm/llvm-project/pull/71234

>From 91c64e83b3d8d405e71f8e3108483b88ee4758d8 Mon Sep 17 00:00:00 2001
From: Saiyedul Islam 
Date: Fri, 3 Nov 2023 16:16:25 -0500
Subject: [PATCH 1/3] [OpenMP] Cleanup and fixes for ABI agnostic DeviceRTL

Fixes the DeviceRTL compilation to ensure it is ABI agnostic.
Uses already available global variable "oclc_ABI_version" instead
of "llvm.amdgcn.abi.verion".

It also adds some minor fields in ImplicitArg structure.
---
 clang/include/clang/Basic/TargetOptions.h |  2 +-
 clang/lib/CodeGen/CGBuiltin.cpp   |  6 +-
 clang/lib/CodeGen/Targets/AMDGPU.cpp  |  5 +-
 clang/test/CodeGen/amdgpu-abi-version.c   |  4 +-
 clang/test/CodeGen/amdgpu-address-spaces.cpp  |  2 +-
 .../amdgpu-code-object-version-linking.cu | 16 +++---
 .../test/CodeGenCUDA/amdgpu-workgroup-size.cu |  6 +-
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 57 +++
 .../amdgpu/utils/UtilitiesRTL.h   |  4 +-
 9 files changed, 82 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/Basic/TargetOptions.h 
b/clang/include/clang/Basic/TargetOptions.h
index ba3acd029587160..7497e580d27338d 100644
--- a/clang/include/clang/Basic/TargetOptions.h
+++ b/clang/include/clang/Basic/TargetOptions.h
@@ -88,7 +88,7 @@ class TargetOptions {
 COV_5 = 500,
   };
   /// \brief Code object version for AMDGPU.
-  CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_None;
+  CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_4;
 
   /// \brief Enumeration values for AMDGPU printf lowering scheme
   enum class AMDGPUPrintfKind {
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 5ab81cc605819c3..44a8133ff61ce67 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17468,11 +17468,11 @@ Value *EmitAMDGPUImplicitArgPtr(CodeGenFunction ) 
{
 /// Emit code based on Code Object ABI version.
 /// COV_4: Emit code to use dispatch ptr
 /// COV_5: Emit code to use implicitarg ptr
-/// COV_NONE : Emit code to load a global variable "llvm.amdgcn.abi.version"
+/// COV_NONE : Emit code to load a global variable "__oclc_ABI_version"
 ///and use its value for COV_4 or COV_5 approach. It is used for
 ///compiling device libraries in an ABI-agnostic way.
 ///
-/// Note: "llvm.amdgcn.abi.version" is supposed to be emitted and intialized by
+/// Note: "__oclc_ABI_version" is supposed to be emitted and intialized by
 ///   clang during compilation of user code.
 Value *EmitAMDGPUWorkGroupSize(CodeGenFunction , unsigned Index) {
   llvm::LoadInst *LD;
@@ -17480,7 +17480,7 @@ Value *EmitAMDGPUWorkGroupSize(CodeGenFunction , 
unsigned Index) {
   auto Cov = CGF.getTarget().getTargetOpts().CodeObjectVersion;
 
   if (Cov == clang::TargetOptions::COV_None) {
-StringRef Name = "llvm.amdgcn.abi.version";
+StringRef Name = "__oclc_ABI_version";
 auto *ABIVersionC = CGF.CGM.getModule().getNamedGlobal(Name);
 if (!ABIVersionC)
   ABIVersionC = new llvm::GlobalVariable(
diff --git a/clang/lib/CodeGen/Targets/AMDGPU.cpp 
b/clang/lib/CodeGen/Targets/AMDGPU.cpp
index 0411846cf9b02bd..d793d27e0db8b80 100644
--- a/clang/lib/CodeGen/Targets/AMDGPU.cpp
+++ b/clang/lib/CodeGen/Targets/AMDGPU.cpp
@@ -362,11 +362,14 @@ void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
 /// AMDGPU ROCm device libraries.
 void AMDGPUTargetCodeGenInfo::emitTargetGlobals(
 CodeGen::CodeGenModule ) const {
-  StringRef Name = "llvm.amdgcn.abi.version";
+  StringRef Name = "__oclc_ABI_version";
   llvm::GlobalVariable *OriginalGV = CGM.getModule().getNamedGlobal(Name);
   if (OriginalGV && 
!llvm::GlobalVariable::isExternalLinkage(OriginalGV->getLinkage()))
 return;
 
+  if(CGM.getTarget().getTargetOpts().CodeObjectVersion == 
clang::TargetOptions::COV_None)
+return;
+
   auto *Type = llvm::IntegerType::getIntNTy(CGM.getModule().getContext(), 32);
   llvm::Constant *COV = llvm::ConstantInt::get(
   Type, CGM.getTarget().getTargetOpts().CodeObjectVersion);
diff --git a/clang/test/CodeGen/amdgpu-abi-version.c 
b/clang/test/CodeGen/amdgpu-abi-version.c
index d1189545139e2a6..4e5ad87655f2305 100644
--- a/clang/test/CodeGen/amdgpu-abi-version.c
+++ b/clang/test/CodeGen/amdgpu-abi-version.c
@@ -2,14 +2,14 @@
 // RUN: %clang_cc1 -cc1 -triple amdgcn-amd-amdhsa -emit-llvm 
-mcode-object-version=none %s -o - | FileCheck %s
 
 //.
-// CHECK: @llvm.amdgcn.abi.version = weak_odr hidden local_unnamed_addr 
addrspace(4) constant i32 0
+// CHECK: @__oclc_ABI_version = external addrspace(4) global i32
 //.
 // CHECK-LABEL: define dso_local i32 @foo(
 // CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[RETVAL:%.*]] = alloca i32, align 4, addrspace(5)
 // CHECK-NEXT:[[RETVAL_ASCAST:%.*]] = addrspacecast ptr addrspace(5) 
[[RETVAL]] to ptr
-// CHECK-NEXT:[[TMP0:%.*]] = load 

[clang] Revert "Revert "[AMDGPU] const-fold imm operands of (PR #71669)

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

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


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


[clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71755)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/71755

>From c85d3c4879a5ff9d6f3ab318ebd7b63410249062 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 8 Nov 2023 17:55:56 -0800
Subject: [PATCH] [clang-format] Handle variable declarations in
 BreakAfterAttributes

Also cleaned up some old test cases.

Fixes #71563.
---
 clang/docs/ClangFormatStyleOptions.rst | 13 +++--
 clang/include/clang/Format/Format.h| 13 +++--
 clang/lib/Format/TokenAnnotator.cpp| 33 --
 clang/unittests/Format/FormatTest.cpp  | 38 ++
 4 files changed, 67 insertions(+), 30 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 21342e1b89ea866..d496fc85f7ae71a 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,8 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a function
-  declaration/definition name.
+  Break after a group of C++11 attributes before a variable/function
+  (including constructor/destructor) declaration/definition name.
 
   Possible values:
 
@@ -2059,6 +2059,10 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]]
+  const int i;
+  [[gnu::const]] [[maybe_unused]]
+  int j;
   [[nodiscard]]
   inline int f();
   [[gnu::const]] [[nodiscard]]
@@ -2069,6 +2073,9 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]] const int i;
+  [[gnu::const]] [[maybe_unused]]
+  int j;
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
@@ -2078,6 +2085,8 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]] const int i;
+  [[gnu::const]] [[maybe_unused]] int j;
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]] int g();
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3e9d1915badd87f..9442344000e142b 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1428,6 +1428,10 @@ struct FormatStyle {
   enum AttributeBreakingStyle : int8_t {
 /// Always break after attributes.
 /// \code
+///   [[maybe_unused]]
+///   const int i;
+///   [[gnu::const]] [[maybe_unused]]
+///   int j;
 ///   [[nodiscard]]
 ///   inline int f();
 ///   [[gnu::const]] [[nodiscard]]
@@ -1436,6 +1440,9 @@ struct FormatStyle {
 ABS_Always,
 /// Leave the line breaking after attributes as is.
 /// \code
+///   [[maybe_unused]] const int i;
+///   [[gnu::const]] [[maybe_unused]]
+///   int j;
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
@@ -1443,14 +1450,16 @@ struct FormatStyle {
 ABS_Leave,
 /// Never break after attributes.
 /// \code
+///   [[maybe_unused]] const int i;
+///   [[gnu::const]] [[maybe_unused]] int j;
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]] int g();
 /// \endcode
 ABS_Never,
   };
 
-  /// Break after a group of C++11 attributes before a function
-  /// declaration/definition name.
+  /// Break after a group of C++11 attributes before a variable/function
+  /// (including constructor/destructor) declaration/definition name.
   /// \version 16
   AttributeBreakingStyle BreakAfterAttributes;
 
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 729e7e370bf62ea..210152d0846f4f9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2000,6 +2000,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = 
   Current.setType(TT_StartOfName);
+  if (auto *PrevNonComment = Current.getPreviousNonComment();
+  PrevNonComment && PrevNonComment->is(TT_StartOfName)) {
+PrevNonComment->setType(TT_Unknown);
+  }
 } else if (Current.is(tok::semi)) {
   // Reset FirstStartOfName after finding a semicolon so that a for loop
   // with multiple increment statements is not confused with a for loop
@@ -3258,7 +3262,7 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   if (Current.is(TT_FunctionDeclarationName))
 return true;
 
-  if (!Current.Tok.getIdentifierInfo())
+  if (!Current.Tok.getIdentifierInfo() || Current.is(TT_CtorDtorDeclName))
 return false;
 
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
@@ -3441,29 +3445,28 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {

[clang] Revert "Revert "[AMDGPU] const-fold imm operands of (PR #71669)

2023-11-08 Thread Pravin Jagtap via cfe-commits

https://github.com/pravinjagtap updated 
https://github.com/llvm/llvm-project/pull/71669

>From 63f870074df10d0e2624632ac2ab0cb0996b436c Mon Sep 17 00:00:00 2001
From: Pravin Jagtap 
Date: Wed, 8 Nov 2023 07:08:03 -0500
Subject: [PATCH 1/2] Revert "Revert "[AMDGPU] const-fold imm operands of
 amdgcn_update_dpp intrinsic (#71139)""

This reverts commit d1fb9307951319eea3e869d78470341d603c8363 and fixes
the lit test clang/test/CodeGenHIP/dpp-const-fold.hip
---
 clang/lib/CodeGen/CGBuiltin.cpp  | 84 +---
 clang/lib/CodeGen/CodeGenFunction.h  |  2 +
 clang/test/CodeGenHIP/dpp-const-fold.hip | 48 ++
 3 files changed, 81 insertions(+), 53 deletions(-)
 create mode 100644 clang/test/CodeGenHIP/dpp-const-fold.hip

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 5ab81cc605819c3..e7e498e8a933131 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -5708,18 +5708,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 llvm::FunctionType *FTy = F->getFunctionType();
 
 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
-  Value *ArgValue;
-  // If this is a normal argument, just emit it as a scalar.
-  if ((ICEArguments & (1 << i)) == 0) {
-ArgValue = EmitScalarExpr(E->getArg(i));
-  } else {
-// If this is required to be a constant, constant fold it so that we
-// know that the generated intrinsic gets a ConstantInt.
-ArgValue = llvm::ConstantInt::get(
-getLLVMContext(),
-*E->getArg(i)->getIntegerConstantExpr(getContext()));
-  }
-
+  Value *ArgValue = EmitScalarOrConstFoldImmArg(ICEArguments, i, E);
   // If the intrinsic arg type is different from the builtin arg type
   // we need to do a bit cast.
   llvm::Type *PTy = FTy->getParamType(i);
@@ -8599,15 +8588,7 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned 
BuiltinID,
   }
 }
 
-if ((ICEArguments & (1 << i)) == 0) {
-  Ops.push_back(EmitScalarExpr(E->getArg(i)));
-} else {
-  // If this is required to be a constant, constant fold it so that we know
-  // that the generated intrinsic gets a ConstantInt.
-  Ops.push_back(llvm::ConstantInt::get(
-  getLLVMContext(),
-  *E->getArg(i)->getIntegerConstantExpr(getContext(;
-}
+Ops.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, i, E));
   }
 
   switch (BuiltinID) {
@@ -11094,15 +11075,7 @@ Value 
*CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID,
 continue;
   }
 }
-if ((ICEArguments & (1 << i)) == 0) {
-  Ops.push_back(EmitScalarExpr(E->getArg(i)));
-} else {
-  // If this is required to be a constant, constant fold it so that we know
-  // that the generated intrinsic gets a ConstantInt.
-  Ops.push_back(llvm::ConstantInt::get(
-  getLLVMContext(),
-  *E->getArg(i)->getIntegerConstantExpr(getContext(;
-}
+Ops.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, i, E));
   }
 
   auto SISDMap = ArrayRef(AArch64SISDIntrinsicMap);
@@ -13814,16 +13787,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
   assert(Error == ASTContext::GE_None && "Should not codegen an error");
 
   for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) {
-// If this is a normal argument, just emit it as a scalar.
-if ((ICEArguments & (1 << i)) == 0) {
-  Ops.push_back(EmitScalarExpr(E->getArg(i)));
-  continue;
-}
-
-// If this is required to be a constant, constant fold it so that we know
-// that the generated intrinsic gets a ConstantInt.
-Ops.push_back(llvm::ConstantInt::get(
-getLLVMContext(), 
*E->getArg(i)->getIntegerConstantExpr(getContext(;
+Ops.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, i, E));
   }
 
   // These exist so that the builtin that takes an immediate can be bounds
@@ -17588,6 +17552,23 @@ void CodeGenFunction::ProcessOrderScopeAMDGCN(Value 
*Order, Value *Scope,
   SSID = getLLVMContext().getOrInsertSyncScopeID(scp);
 }
 
+llvm::Value *CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned 
ICEArguments,
+  unsigned Idx,
+  const CallExpr *E) {
+  llvm::Value *Arg = nullptr;
+  if ((ICEArguments & (1 << Idx)) == 0) {
+Arg = EmitScalarExpr(E->getArg(Idx));
+  } else {
+// If this is required to be a constant, constant fold it so that we
+// know that the generated intrinsic gets a ConstantInt.
+std::optional Result =
+E->getArg(Idx)->getIntegerConstantExpr(getContext());
+assert(Result && "Expected argument to be a constant");
+Arg = llvm::ConstantInt::get(getLLVMContext(), *Result);
+  }
+  return Arg;
+}
+
 Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned BuiltinID,
   

[clang] Revert "Revert "[AMDGPU] const-fold imm operands of (PR #71669)

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


@@ -0,0 +1,48 @@
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang --offload-arch=gfx906 -S -o - -emit-llvm --cuda-device-only 
-nogpuinc -nogpulib\

arsenm wrote:

This should use %clang_cc1, look at some of the other CodeGen* test run lines 
for examples 

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


[llvm] [clang] [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (PR #71014)

2023-11-08 Thread Wei Wang via cfe-commits

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


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


[llvm] [clang] [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (PR #71014)

2023-11-08 Thread Wei Wang via cfe-commits


@@ -0,0 +1,59 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++20 \
+// RUN: -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++20 \
+// RUN: -O3 -emit-llvm %s -o - | FileCheck %s --check-prefix=CHECK-O
+
+#include "Inputs/coroutine.h"
+
+using namespace std;
+
+struct A;
+struct A_promise_type {
+  A get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend() noexcept;
+  void return_value(int);
+  void unhandled_exception();
+
+  std::coroutine_handle<> handle;
+};
+
+struct Awaitable{
+  bool await_ready();
+  int await_resume();
+  template 
+  void await_suspend(F);
+};
+Awaitable something();
+
+struct dtor {
+dtor();
+~dtor();
+};
+
+struct [[clang::coro_only_destroy_when_complete]] A {

apolloww wrote:

Thanks for the explaination

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


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

2023-11-08 Thread Evgenii Kudriashov via cfe-commits

e-kud wrote:

I'm a little bit confused, What's the expected behavior of `+avx10.1-512 
-avx10.1-256` in codegen aspect. Should we generate only instructions in the 
difference of sets? Or do we consider `avx10.1-256` as a base of `avx10.1-512` 
and if it is disabled `avx10.1-512` can't be enabled?

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


[clang] [clang][analyzer] Support `fputc` in StreamChecker (PR #71518)

2023-11-08 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/71518

>From 2ebbb60c04968f9c953790daa5c791f072d975b8 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Tue, 7 Nov 2023 16:44:05 +0800
Subject: [PATCH] [clang][analyzer] Support `fputc` in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 61 ---
 clang/test/Analysis/stream-error.c| 51 
 clang/test/Analysis/stream.c  |  6 ++
 3 files changed, 110 insertions(+), 8 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 898906977ba9bb6..a4b367a5599f58f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -245,11 +245,14 @@ class StreamChecker : public CheckerStreamArgNo), C,
@@ -650,7 +656,7 @@ void StreamChecker::preFreadFwrite(const FnDescription 
*Desc,
   if (!State)
 return;
 
-  if (!IsFread) {
+  if (!IsRead) {
 C.addTransition(State);
 return;
   }
@@ -745,6 +751,45 @@ void StreamChecker::evalFreadFwrite(const FnDescription 
*Desc,
 C.addTransition(StateFailed);
 }
 
+void StreamChecker::evalFputc(const FnDescription *Desc, const CallEvent ,
+  CheckerContext ) const {
+  ProgramStateRef State = C.getState();
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  if (!StreamSym)
+return;
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  const StreamState *OldSS = State->get(StreamSym);
+  if (!OldSS)
+return;
+
+  assertStreamStateOpened(OldSS);
+
+  // `fputc` returns the written character on success, otherwise returns EOF.
+
+  // Generate a transition for the success state.
+  std::optional PutVal = Call.getArgSVal(0).getAs();
+  if (!PutVal)
+return;
+  ProgramStateRef StateNotFailed =
+  State->BindExpr(CE, C.getLocationContext(), *PutVal);
+  StateNotFailed =
+  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  C.addTransition(StateNotFailed);
+
+  // Add transition for the failed state.
+  // If a (non-EOF) error occurs, the resulting value of the file position
+  // indicator for the stream is indeterminate.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+  StreamState NewSS = StreamState::getOpened(
+  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StateFailed = StateFailed->set(StreamSym, NewSS);
+  C.addTransition(StateFailed);
+}
+
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent ,
  CheckerContext ) const {
   ProgramStateRef State = C.getState();
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 3c00e59bb6bd19d..45bebac02e49f85 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,23 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fputc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fputc('X', F);
+  if (Ret == EOF) {
+clang_analyzer_eval(ferror(F)); // expected-warning {{TRUE}}
+fputc('Y', F); // expected-warning {{might be 'indeterminate'}}
+  } else {
+clang_analyzer_eval(Ret == 'X'); // expected-warning {{TRUE}}
+clang_analyzer_eval(ferror(F)); // expected-warning {{FALSE}}
+fputc('Y', F); // no-warning
+  }
+  fclose(F);
+  fputc('A', F); // expected-warning {{Stream might be already closed}}
+}
+
 void freadwrite_zerosize(FILE *F) {
   size_t Ret;
   Ret = fwrite(0, 1, 0, F);
@@ -241,6 +258,23 @@ void error_indeterminate_clearerr(void) {
   fclose(F);
 }
 
+void error_indeterminate_fputc(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  int rc = fseek(F, 0, SEEK_SET);
+  if (rc) {
+if (feof(F)) {
+  fputc('X', F); // no warning
+} else if (ferror(F)) {
+  fputc('C', F); // expected-warning {{might be 'indeterminate'}}
+} else {
+  fputc('E', F); // expected-warning {{might be 'indeterminate'}}
+}
+  }
+  fclose(F);
+}
+
 void error_indeterminate_feof1(void) {
   FILE *F = fopen("file", "r+");
   if (!F)
@@ -268,3 +302,20 @@ void error_indeterminate_feof2(void) {
   }
   fclose(F);
 }
+
+void error_indeterminate_feof3(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  char Buf[10];
+  if (fread(Buf, 1, 10, F) < 10) {
+if (feof(F)) {
+  // error is feof, should be non-indeterminate
+  fputc(';', F); // no warning
+}
+if (ferror(F)) {
+  fputc('=', F); // expected-warning {{might be 'indeterminate'}}
+}
+  }
+  fclose(F);
+}
diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c
index a01310cfef5dd8a..9b6a31738d6e0b8 100644
--- a/clang/test/Analysis/stream.c
+++ b/clang/test/Analysis/stream.c
@@ -14,6 +14,12 @@ void 

[clang] [clang][analyzer] Support `fputc` in StreamChecker (PR #71518)

2023-11-08 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/71518

>From 7918014a23d4e4e996896164139dafe3c98aa8a5 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Tue, 7 Nov 2023 16:44:05 +0800
Subject: [PATCH] [clang][analyzer] Support `fputc` in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 61 ---
 clang/test/Analysis/stream-error.c| 51 
 clang/test/Analysis/stream.c  | 14 +
 3 files changed, 118 insertions(+), 8 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 898906977ba9bb6..a4b367a5599f58f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -245,11 +245,14 @@ class StreamChecker : public CheckerStreamArgNo), C,
@@ -650,7 +656,7 @@ void StreamChecker::preFreadFwrite(const FnDescription 
*Desc,
   if (!State)
 return;
 
-  if (!IsFread) {
+  if (!IsRead) {
 C.addTransition(State);
 return;
   }
@@ -745,6 +751,45 @@ void StreamChecker::evalFreadFwrite(const FnDescription 
*Desc,
 C.addTransition(StateFailed);
 }
 
+void StreamChecker::evalFputc(const FnDescription *Desc, const CallEvent ,
+  CheckerContext ) const {
+  ProgramStateRef State = C.getState();
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  if (!StreamSym)
+return;
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  const StreamState *OldSS = State->get(StreamSym);
+  if (!OldSS)
+return;
+
+  assertStreamStateOpened(OldSS);
+
+  // `fputc` returns the written character on success, otherwise returns EOF.
+
+  // Generate a transition for the success state.
+  std::optional PutVal = Call.getArgSVal(0).getAs();
+  if (!PutVal)
+return;
+  ProgramStateRef StateNotFailed =
+  State->BindExpr(CE, C.getLocationContext(), *PutVal);
+  StateNotFailed =
+  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  C.addTransition(StateNotFailed);
+
+  // Add transition for the failed state.
+  // If a (non-EOF) error occurs, the resulting value of the file position
+  // indicator for the stream is indeterminate.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+  StreamState NewSS = StreamState::getOpened(
+  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StateFailed = StateFailed->set(StreamSym, NewSS);
+  C.addTransition(StateFailed);
+}
+
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent ,
  CheckerContext ) const {
   ProgramStateRef State = C.getState();
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 3c00e59bb6bd19d..45bebac02e49f85 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,23 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fputc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fputc('X', F);
+  if (Ret == EOF) {
+clang_analyzer_eval(ferror(F)); // expected-warning {{TRUE}}
+fputc('Y', F); // expected-warning {{might be 'indeterminate'}}
+  } else {
+clang_analyzer_eval(Ret == 'X'); // expected-warning {{TRUE}}
+clang_analyzer_eval(ferror(F)); // expected-warning {{FALSE}}
+fputc('Y', F); // no-warning
+  }
+  fclose(F);
+  fputc('A', F); // expected-warning {{Stream might be already closed}}
+}
+
 void freadwrite_zerosize(FILE *F) {
   size_t Ret;
   Ret = fwrite(0, 1, 0, F);
@@ -241,6 +258,23 @@ void error_indeterminate_clearerr(void) {
   fclose(F);
 }
 
+void error_indeterminate_fputc(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  int rc = fseek(F, 0, SEEK_SET);
+  if (rc) {
+if (feof(F)) {
+  fputc('X', F); // no warning
+} else if (ferror(F)) {
+  fputc('C', F); // expected-warning {{might be 'indeterminate'}}
+} else {
+  fputc('E', F); // expected-warning {{might be 'indeterminate'}}
+}
+  }
+  fclose(F);
+}
+
 void error_indeterminate_feof1(void) {
   FILE *F = fopen("file", "r+");
   if (!F)
@@ -268,3 +302,20 @@ void error_indeterminate_feof2(void) {
   }
   fclose(F);
 }
+
+void error_indeterminate_feof3(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  char Buf[10];
+  if (fread(Buf, 1, 10, F) < 10) {
+if (feof(F)) {
+  // error is feof, should be non-indeterminate
+  fputc(';', F); // no warning
+}
+if (ferror(F)) {
+  fputc('=', F); // expected-warning {{might be 'indeterminate'}}
+}
+  }
+  fclose(F);
+}
diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c
index a01310cfef5dd8a..c4e00ed7ffadb64 100644
--- a/clang/test/Analysis/stream.c
+++ b/clang/test/Analysis/stream.c
@@ -14,6 +14,12 @@ void 

[libcxx] [compiler-rt] [clang] [lld] [flang] [libcxxabi] [clang-tools-extra] [llvm] [libc] [libc++] Fix the behavior of throwing `operator new` under -fno-exceptions (PR #69498)

2023-11-08 Thread Louis Dionne via cfe-commits

https://github.com/ldionne updated 
https://github.com/llvm/llvm-project/pull/69498

>From 77c0256c3ae99808a8def68bfcf5eee2fad704ca Mon Sep 17 00:00:00 2001
From: Louis Dionne 
Date: Wed, 14 Jun 2023 17:49:22 -0700
Subject: [PATCH 1/9] [libc++] Fix the behavior of throwing `operator new`
 under -fno-exceptions

In D144319, Clang tried to land a change that would cause some functions
that are not supposed to return nullptr to optimize better. As reported
in https://reviews.llvm.org/D144319#4203982, libc++ started seeing failures
in its CI shortly after this change was landed.

As explained in D146379, the reason for these failures is that libc++'s
throwing `operator new` can in fact return nullptr when compiled with
exceptions disabled. However, this contradicts the Standard, which
clearly says that the throwing version of `operator new(size_t)`
should never return nullptr. This is actually a long standing issue.
I've previously seen a case where LTO would optimize incorrectly based
on the assumption that `operator new` doesn't return nullptr, an
assumption that was violated in that case because libc++.dylib was
compiled with -fno-exceptions.

Unfortunately, fixing this is kind of tricky. The Standard has a few
requirements for the allocation functions, some of which are impossible
to satisfy under -fno-exceptions:
1. `operator new(size_t)` must never return nullptr
2. `operator new(size_t, nothrow_t)` must call the throwing version
 and return nullptr on failure to allocate
3. We can't throw exceptions when compiled with -fno-exceptions

In the case where exceptions are enabled, things work nicely. `new(size_t)`
throws and `new(size_t, nothrow_t)` uses a try-catch to return nullptr.
However, when compiling the library with -fno-exceptions, we can't throw
an exception from `new(size_t)`, and we can't catch anything from
`new(size_t, nothrow_t)`. The only thing we can do from `new(size_t)`
is actually abort the program, which does not make it possible for
`new(size_t, nothrow_t)` to catch something and return nullptr.

This patch makes the following changes:
1. When compiled with -fno-exceptions, the throwing version of
   `operator new` will now abort on failure instead of returning
   nullptr on failure. This resolves the issue that the compiler
   could mis-compile based on the assumption that nullptr is never
   returned. This constitutes an API and ABI breaking change for
   folks compiling the library with -fno-exceptions (which is not
   the general public, who merely uses libc++ headers but use a
   shared library that has already been compiled). This should mostly
   impact vendors and other folks who compile libc++.dylib themselves.

2. When the library is compiled with -fexceptions, the nothrow version
   of `operator new` has no change. When the library is compiled with
   -fno-exceptions, the nothrow version of `operator new` will now check
   whether the throwing version of `operator new` has been overridden.
   If it has not been overridden, then it will use an implementation
   equivalent to that of the throwing `operator new`, except it will
   return nullptr on failure to allocate (instead of terminating).
   However, if the throwing `operator new` has been overridden, it is
   now an error NOT to also override the nothrow `operator new`. Indeed,
   there is no way for us to implement a valid nothrow `operator new`
   without knowing the exact implementation of the throwing version.

rdar://103958777

Differential Revision: https://reviews.llvm.org/D150610
---
 libcxx/docs/ReleaseNotes/18.rst   | 23 +
 libcxx/include/CMakeLists.txt |  1 +
 libcxx/include/__overridable_function | 38 
 libcxx/include/new|  9 +-
 libcxx/src/new.cpp| 79 +++-
 ...new_not_overridden_fno_exceptions.pass.cpp | 56 
 .../new_dont_return_nullptr.pass.cpp  | 37 
 libcxx/test/support/check_assertion.h |  6 ++
 libcxxabi/src/stdlib_new_delete.cpp   | 90 ++-
 9 files changed, 291 insertions(+), 48 deletions(-)
 create mode 100644 libcxx/include/__overridable_function
 create mode 100644 
libcxx/test/libcxx/language.support/support.dynamic/assert.nothrow_new_not_overridden_fno_exceptions.pass.cpp
 create mode 100644 
libcxx/test/libcxx/language.support/support.dynamic/new_dont_return_nullptr.pass.cpp

diff --git a/libcxx/docs/ReleaseNotes/18.rst b/libcxx/docs/ReleaseNotes/18.rst
index ac78563aa73848f..bf017613a01b892 100644
--- a/libcxx/docs/ReleaseNotes/18.rst
+++ b/libcxx/docs/ReleaseNotes/18.rst
@@ -118,6 +118,29 @@ LLVM 20
 ABI Affecting Changes
 -
 
+- When the shared/static library is built with ``-fno-exceptions``, the 
behavior of ``operator new`` was changed
+  to make it standards-conforming. In LLVM 17 and before, the throwing 
versions of ``operator new`` would return
+  ``nullptr`` upon failure to allocate, when 

[clang] [clang-format] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

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

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


[clang] 68d618f - [clang-format] Add ability for clang-format-diff to exit with non-0 status (#70883)

2023-11-08 Thread via cfe-commits

Author: Conrad Donahue
Date: 2023-11-08T18:13:03-08:00
New Revision: 68d618f908458e7513e2a56be292216ea0e4ef3f

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

LOG: [clang-format] Add ability for clang-format-diff to exit with non-0 status 
(#70883)

This patch adds the ability for the clang-format-diff script to exit
with a non-zero status if it detects that formatting changes are
necessary. This makes it easier to use clang-format-diff as part of a
DevOps pipeline, since you could add a stage to run clang-format-diff
and fail if the formatting needs to be fixed.

Added: 


Modified: 
clang/tools/clang-format/clang-format-diff.py

Removed: 




diff  --git a/clang/tools/clang-format/clang-format-
diff .py b/clang/tools/clang-format/clang-format-
diff .py
index 324ef5b7f6b35f6..892c1e38a462ff4 100755
--- a/clang/tools/clang-format/clang-format-
diff .py
+++ b/clang/tools/clang-format/clang-format-
diff .py
@@ -185,6 +185,7 @@ def main():
 
diff _string = "".join(
diff )
 if len(
diff _string) > 0:
 sys.stdout.write(
diff _string)
+sys.exit(1)
 
 
 if __name__ == "__main__":



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


[clang] [clang-format] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

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

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


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


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

2023-11-08 Thread Shengchen Kan via cfe-commits


@@ -131,35 +135,50 @@ bool X86TargetInfo::initFeatureMap(
   continue;
 }
 
-if (Feature.substr(0, 7) == "+avx10.") {
-  HasAVX10 = true;
-  HasAVX512F = true;
-  if (Feature.substr(Feature.size() - 3, 3) == "512") {
-HasEVEX512 = true;
-  } else if (Feature.substr(7, 2) == "1-") {
-HasEVEX512 = false;
+if (Feature.substr(1, 6) == "avx10.") {
+  if (Feature[0] == '+') {
+HasAVX10 = true;
+if (Feature.substr(Feature.size() - 3, 3) == "512")
+  HasAVX10_512 = true;
+LastAVX10 = Feature;
+  } else if (HasAVX10 && Feature == "-avx10.1-256") {
+HasAVX10 = false;
+HasAVX10_512 = false;
+  } else if (HasAVX10_512 && Feature == "-avx10.1-512") {
+HasAVX10_512 = false;
   }
+  // Postpone AVX10 features handling after AVX512 settled.
+  UpdatedAVX10FeaturesVec.push_back(Feature);
+  continue;
 } else if (!HasAVX512F && Feature.substr(0, 7) == "+avx512") {
   HasAVX512F = true;
+  LastAVX512 = Feature;
 } else if (HasAVX512F && Feature == "-avx512f") {
   HasAVX512F = false;
-} else if (HasAVX10 && Feature == "-avx10.1-256") {
-  HasAVX10 = false;
-  HasAVX512F = false;
-} else if (!HasEVEX512 && Feature == "+evex512") {
+} else if (HasEVEX512 != true && Feature == "+evex512") {
   HasEVEX512 = true;
-} else if (HasEVEX512 && Feature == "-avx10.1-512") {
-  HasEVEX512 = false;
-} else if (HasEVEX512 && Feature == "-evex512") {
+  continue;
+} else if (HasEVEX512 != false && Feature == "-evex512") {
   HasEVEX512 = false;
+  continue;
 }
 
 UpdatedFeaturesVec.push_back(Feature);
   }
-  if (HasAVX512F && HasEVEX512)
-UpdatedFeaturesVec.push_back("+evex512");
-  else if (HasAVX10)
-UpdatedFeaturesVec.push_back("-evex512");
+  llvm::append_range(UpdatedFeaturesVec, UpdatedAVX10FeaturesVec);

KanRobert wrote:

I see.

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


[clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71755)

2023-11-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Also cleaned up some old test cases.

Fixes #71563.

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


4 Files Affected:

- (modified) clang/docs/ClangFormatStyleOptions.rst (+2-2) 
- (modified) clang/include/clang/Format/Format.h (+2-2) 
- (modified) clang/lib/Format/TokenAnnotator.cpp (+18-15) 
- (modified) clang/unittests/Format/FormatTest.cpp (+27-11) 


``diff
diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 21342e1b89ea866..3b9c4bcf19b2c2d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,8 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a function
-  declaration/definition name.
+  Break after a group of C++11 attributes before a variable/function
+  (including constructor/destructor) declaration/definition name.
 
   Possible values:
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3e9d1915badd87f..8282f9206ddd2fd 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1449,8 +1449,8 @@ struct FormatStyle {
 ABS_Never,
   };
 
-  /// Break after a group of C++11 attributes before a function
-  /// declaration/definition name.
+  /// Break after a group of C++11 attributes before a variable/function
+  /// (including constructor/destructor) declaration/definition name.
   /// \version 16
   AttributeBreakingStyle BreakAfterAttributes;
 
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 729e7e370bf62ea..210152d0846f4f9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2000,6 +2000,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = 
   Current.setType(TT_StartOfName);
+  if (auto *PrevNonComment = Current.getPreviousNonComment();
+  PrevNonComment && PrevNonComment->is(TT_StartOfName)) {
+PrevNonComment->setType(TT_Unknown);
+  }
 } else if (Current.is(tok::semi)) {
   // Reset FirstStartOfName after finding a semicolon so that a for loop
   // with multiple increment statements is not confused with a for loop
@@ -3258,7 +3262,7 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   if (Current.is(TT_FunctionDeclarationName))
 return true;
 
-  if (!Current.Tok.getIdentifierInfo())
+  if (!Current.Tok.getIdentifierInfo() || Current.is(TT_CtorDtorDeclName))
 return false;
 
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
@@ -3441,29 +3445,28 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
   if (AlignArrayOfStructures)
 calculateArrayInitializerColumnList(Line);
 
+  const bool IsCpp = Style.isCpp();
   bool LineIsFunctionDeclaration = false;
   FormatToken *ClosingParen = nullptr;
   for (FormatToken *Tok = Current, *AfterLastAttribute = nullptr; Tok;
Tok = Tok->Next) {
 if (Tok->Previous->EndsCppAttributeGroup)
   AfterLastAttribute = Tok;
-if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
-IsCtorOrDtor ||
-isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
-  if (!IsCtorOrDtor) {
-LineIsFunctionDeclaration = true;
-Tok->setFinalizedType(TT_FunctionDeclarationName);
-  }
-  if (AfterLastAttribute &&
-  mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
-AfterLastAttribute->MustBreakBefore = true;
-Line.ReturnTypeWrapped = true;
-  }
-  break;
+LineIsFunctionDeclaration =
+isFunctionDeclarationName(IsCpp, *Tok, Line, ClosingParen);
+if (LineIsFunctionDeclaration)
+  Tok->setFinalizedType(TT_FunctionDeclarationName);
+else if (!Tok->isOneOf(TT_CtorDtorDeclName, TT_StartOfName))
+  continue;
+if (AfterLastAttribute &&
+mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
+  AfterLastAttribute->MustBreakBefore = true;
+  Line.ReturnTypeWrapped = true;
 }
+break;
   }
 
-  if (Style.isCpp()) {
+  if (IsCpp) {
 if (!LineIsFunctionDeclaration) {
   // Annotate */&/&& in `operator` function calls as binary operators.
   for (const auto *Tok = Line.First; Tok; Tok = Tok->Next) {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 80903e7630c8073..dcd05b4175e0b94 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8479,18 +8479,25 @@ TEST_F(FormatTest, 
BreaksFunctionDeclarationsWithTrailingTokens) {
   

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

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


@@ -334,6 +335,15 @@ template<> struct simplify_type {
   }
 };
 
+template <> struct GraphTraits {

wenju-he wrote:

> For the specific problem here, I'd consider expanding all constant 
> expressions in the function upfront, and then not having to deal with it.

is it right that I can use convertUsersOfConstantsToInstructions to expand 
constantexp to instructions? However, convertUsersOfConstantsToInstructions 
changes other functions as well. An option to add an addition function 
parameter to convertUsersOfConstantsToInstructions to ensure only constexpr 
users in the function is expanded. @nikic WDYT of this option?

convertUsersOfConstantsToInstructions is also doing a DFS on user of User.

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


[clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71755)

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

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/71755

Also cleaned up some old test cases.

Fixes #71563.

>From 40769fdc8163e61c8a89bc983a7fa50b08ba5e04 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 8 Nov 2023 17:55:56 -0800
Subject: [PATCH] [clang-format] Handle variable declarations in
 BreakAfterAttributes

Also cleaned up some old test cases.

Fixes #71563.
---
 clang/docs/ClangFormatStyleOptions.rst |  4 +--
 clang/include/clang/Format/Format.h|  4 +--
 clang/lib/Format/TokenAnnotator.cpp| 33 --
 clang/unittests/Format/FormatTest.cpp  | 38 ++
 4 files changed, 49 insertions(+), 30 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 21342e1b89ea866..3b9c4bcf19b2c2d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,8 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a function
-  declaration/definition name.
+  Break after a group of C++11 attributes before a variable/function
+  (including constructor/destructor) declaration/definition name.
 
   Possible values:
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3e9d1915badd87f..8282f9206ddd2fd 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1449,8 +1449,8 @@ struct FormatStyle {
 ABS_Never,
   };
 
-  /// Break after a group of C++11 attributes before a function
-  /// declaration/definition name.
+  /// Break after a group of C++11 attributes before a variable/function
+  /// (including constructor/destructor) declaration/definition name.
   /// \version 16
   AttributeBreakingStyle BreakAfterAttributes;
 
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 729e7e370bf62ea..210152d0846f4f9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2000,6 +2000,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = 
   Current.setType(TT_StartOfName);
+  if (auto *PrevNonComment = Current.getPreviousNonComment();
+  PrevNonComment && PrevNonComment->is(TT_StartOfName)) {
+PrevNonComment->setType(TT_Unknown);
+  }
 } else if (Current.is(tok::semi)) {
   // Reset FirstStartOfName after finding a semicolon so that a for loop
   // with multiple increment statements is not confused with a for loop
@@ -3258,7 +3262,7 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   if (Current.is(TT_FunctionDeclarationName))
 return true;
 
-  if (!Current.Tok.getIdentifierInfo())
+  if (!Current.Tok.getIdentifierInfo() || Current.is(TT_CtorDtorDeclName))
 return false;
 
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
@@ -3441,29 +3445,28 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
   if (AlignArrayOfStructures)
 calculateArrayInitializerColumnList(Line);
 
+  const bool IsCpp = Style.isCpp();
   bool LineIsFunctionDeclaration = false;
   FormatToken *ClosingParen = nullptr;
   for (FormatToken *Tok = Current, *AfterLastAttribute = nullptr; Tok;
Tok = Tok->Next) {
 if (Tok->Previous->EndsCppAttributeGroup)
   AfterLastAttribute = Tok;
-if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
-IsCtorOrDtor ||
-isFunctionDeclarationName(Style.isCpp(), *Tok, Line, ClosingParen)) {
-  if (!IsCtorOrDtor) {
-LineIsFunctionDeclaration = true;
-Tok->setFinalizedType(TT_FunctionDeclarationName);
-  }
-  if (AfterLastAttribute &&
-  mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
-AfterLastAttribute->MustBreakBefore = true;
-Line.ReturnTypeWrapped = true;
-  }
-  break;
+LineIsFunctionDeclaration =
+isFunctionDeclarationName(IsCpp, *Tok, Line, ClosingParen);
+if (LineIsFunctionDeclaration)
+  Tok->setFinalizedType(TT_FunctionDeclarationName);
+else if (!Tok->isOneOf(TT_CtorDtorDeclName, TT_StartOfName))
+  continue;
+if (AfterLastAttribute &&
+mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
+  AfterLastAttribute->MustBreakBefore = true;
+  Line.ReturnTypeWrapped = true;
 }
+break;
   }
 
-  if (Style.isCpp()) {
+  if (IsCpp) {
 if (!LineIsFunctionDeclaration) {
   // Annotate */&/&& in `operator` function calls as binary operators.
   for (const auto *Tok = Line.First; Tok; Tok = Tok->Next) {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 

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

2023-11-08 Thread Evgenii Kudriashov via cfe-commits


@@ -131,35 +135,50 @@ bool X86TargetInfo::initFeatureMap(
   continue;
 }
 
-if (Feature.substr(0, 7) == "+avx10.") {
-  HasAVX10 = true;
-  HasAVX512F = true;
-  if (Feature.substr(Feature.size() - 3, 3) == "512") {
-HasEVEX512 = true;
-  } else if (Feature.substr(7, 2) == "1-") {
-HasEVEX512 = false;
+if (Feature.substr(1, 6) == "avx10.") {
+  if (Feature[0] == '+') {
+HasAVX10 = true;
+if (Feature.substr(Feature.size() - 3, 3) == "512")
+  HasAVX10_512 = true;
+LastAVX10 = Feature;
+  } else if (HasAVX10 && Feature == "-avx10.1-256") {
+HasAVX10 = false;
+HasAVX10_512 = false;
+  } else if (HasAVX10_512 && Feature == "-avx10.1-512") {
+HasAVX10_512 = false;
   }
+  // Postpone AVX10 features handling after AVX512 settled.
+  UpdatedAVX10FeaturesVec.push_back(Feature);
+  continue;
 } else if (!HasAVX512F && Feature.substr(0, 7) == "+avx512") {
   HasAVX512F = true;
+  LastAVX512 = Feature;
 } else if (HasAVX512F && Feature == "-avx512f") {
   HasAVX512F = false;
-} else if (HasAVX10 && Feature == "-avx10.1-256") {
-  HasAVX10 = false;
-  HasAVX512F = false;
-} else if (!HasEVEX512 && Feature == "+evex512") {
+} else if (HasEVEX512 != true && Feature == "+evex512") {
   HasEVEX512 = true;
-} else if (HasEVEX512 && Feature == "-avx10.1-512") {
-  HasEVEX512 = false;
-} else if (HasEVEX512 && Feature == "-evex512") {
+  continue;
+} else if (HasEVEX512 != false && Feature == "-evex512") {
   HasEVEX512 = false;
+  continue;
 }
 
 UpdatedFeaturesVec.push_back(Feature);
   }
-  if (HasAVX512F && HasEVEX512)
-UpdatedFeaturesVec.push_back("+evex512");
-  else if (HasAVX10)
-UpdatedFeaturesVec.push_back("-evex512");
+  llvm::append_range(UpdatedFeaturesVec, UpdatedAVX10FeaturesVec);

e-kud wrote:

Nope, there is a `continue` in handling `avx10*` features

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


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

2023-11-08 Thread Shengchen Kan via cfe-commits


@@ -131,35 +135,50 @@ bool X86TargetInfo::initFeatureMap(
   continue;
 }
 
-if (Feature.substr(0, 7) == "+avx10.") {
-  HasAVX10 = true;
-  HasAVX512F = true;
-  if (Feature.substr(Feature.size() - 3, 3) == "512") {
-HasEVEX512 = true;
-  } else if (Feature.substr(7, 2) == "1-") {
-HasEVEX512 = false;
+if (Feature.substr(1, 6) == "avx10.") {
+  if (Feature[0] == '+') {
+HasAVX10 = true;
+if (Feature.substr(Feature.size() - 3, 3) == "512")
+  HasAVX10_512 = true;
+LastAVX10 = Feature;
+  } else if (HasAVX10 && Feature == "-avx10.1-256") {
+HasAVX10 = false;
+HasAVX10_512 = false;
+  } else if (HasAVX10_512 && Feature == "-avx10.1-512") {
+HasAVX10_512 = false;
   }
+  // Postpone AVX10 features handling after AVX512 settled.
+  UpdatedAVX10FeaturesVec.push_back(Feature);
+  continue;
 } else if (!HasAVX512F && Feature.substr(0, 7) == "+avx512") {
   HasAVX512F = true;
+  LastAVX512 = Feature;
 } else if (HasAVX512F && Feature == "-avx512f") {
   HasAVX512F = false;
-} else if (HasAVX10 && Feature == "-avx10.1-256") {
-  HasAVX10 = false;
-  HasAVX512F = false;
-} else if (!HasEVEX512 && Feature == "+evex512") {
+} else if (HasEVEX512 != true && Feature == "+evex512") {
   HasEVEX512 = true;
-} else if (HasEVEX512 && Feature == "-avx10.1-512") {
-  HasEVEX512 = false;
-} else if (HasEVEX512 && Feature == "-evex512") {
+  continue;
+} else if (HasEVEX512 != false && Feature == "-evex512") {
   HasEVEX512 = false;
+  continue;
 }
 
 UpdatedFeaturesVec.push_back(Feature);
   }
-  if (HasAVX512F && HasEVEX512)
-UpdatedFeaturesVec.push_back("+evex512");
-  else if (HasAVX10)
-UpdatedFeaturesVec.push_back("-evex512");
+  llvm::append_range(UpdatedFeaturesVec, UpdatedAVX10FeaturesVec);

KanRobert wrote:

Does it mean the flags for AVX10 Features will be in the vector 
`UpdatedFeaturesVec` 2 times?

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


[llvm] [clang] [Coroutines] Introduce [[clang::coro_only_destroy_when_complete]] (PR #71014)

2023-11-08 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/71014

>From 4531d8b95ecaf08e672939a49fa18415851d136e Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Thu, 2 Nov 2023 11:11:59 +0800
Subject: [PATCH 1/2] [Coroutines] Introduce
 [[clang::coro_only_destroy_when_complete]]

Close https://github.com/llvm/llvm-project/issues/56980.

This patch tries to introduce a light-weight optimizer for coroutines
which are guaranteed to only be destroyed afer it reached the final
suspend.

The rationale behind the patch is simple. See the example:

```C++
A foo() {
  dtor d;
  co_await something();
  dtor d1;
  co_await something();
  dtor d2;
  co_return 43;
}
```

Generally the generated .destroy function may be:

```C++
void foo.destroy(foo.Frame *frame) {
  switch(frame->suspend_index()) {
case 1:
  frame->d.~dtor();
  break;
case 2:
  frame->d.~dtor();
  frame->d1.~dtor();
  break;
case 3:
  frame->d.~dtor();
  frame->d1.~dtor();
  frame->d2.~dtor();
  break;
default: // coroutine completed or haven't started
  break;
  }

  frame->promise.~promise_type();
  delete frame;
}
```

Since the compiler need to be ready for all the cases that the coroutine
may be destroyed in a valid state.

However, from the user's perspective, we can understand that certain
coroutine types may only be destroyed after it reached to the final
suspend point. And we need a method to teach the compiler about this.
Then this is the patch. After the compiler recognized that the
coroutines can only be destroyed after complete, it can optimize the
above example to:

```C++
void foo.destroy(foo.Frame *frame) {
  frame->promise.~promise_type();
  delete frame;
}
```

I spent a lot of time experimenting and experiencing this in the
downstream. The numbers are really good. In a real-world coroutine-heavy
workload, the size of the build dir (including .o files) reduces 14%. And
the size of final libraries (excluding the .o files) reduces 8% in Debug
mode and 1% in Release mode.
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Basic/Attr.td |  12 ++
 clang/include/clang/Basic/AttrDocs.td |  66 +
 clang/lib/CodeGen/CGCoroutine.cpp |   4 +
 .../coro-only-destroy-when-complete.cpp   |  59 
 ...a-attribute-supported-attributes-list.test |   1 +
 llvm/docs/Coroutines.rst  |  11 ++
 llvm/include/llvm/Bitcode/LLVMBitCodes.h  |   1 +
 llvm/include/llvm/IR/Attributes.td|   3 +
 llvm/include/llvm/IR/Function.h   |   7 +
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp |   2 +
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp |   2 +
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp  |  21 ++-
 llvm/lib/Transforms/Utils/CodeExtractor.cpp   |   1 +
 .../coro-only-destroy-when-complete.ll| 137 ++
 15 files changed, 323 insertions(+), 7 deletions(-)
 create mode 100644 
clang/test/CodeGenCoroutines/coro-only-destroy-when-complete.cpp
 create mode 100644 
llvm/test/Transforms/Coroutines/coro-only-destroy-when-complete.ll

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8bac599f88503af..7a131cb520aa600 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -296,6 +296,9 @@ Attribute Changes in Clang
   is ignored, changed from the former incorrect suggestion to move it past
   declaration specifiers. (`#58637 
`_)
 
+- Clang now introduced ``[[clang::coro_only_destroy_when_complete]]`` attribute
+  to reduce the size of the destroy functions for coroutines which are known to
+  be destroyed after having reached the final suspend point.
 
 Improvements to Clang's diagnostics
 ---
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 60b54c155e5..31434565becaec6 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1082,6 +1082,18 @@ def CFConsumed : InheritableParamAttr {
   let Documentation = [RetainBehaviorDocs];
 }
 
+
+// coro_only_destroy_when_complete indicates the coroutines whose return type
+// is marked by coro_only_destroy_when_complete can only be destroyed when the
+// coroutine completes. Then the space for the destroy functions can be saved.
+def CoroOnlyDestroyWhenComplete : InheritableAttr {
+  let Spellings = [Clang<"coro_only_destroy_when_complete">];
+  let Subjects = SubjectList<[CXXRecord]>;
+  let LangOpts = [CPlusPlus];
+  let Documentation = [CoroOnlyDestroyWhenCompleteDocs];
+  let SimpleHandler = 1;
+}
+
 // OSObject-based attributes.
 def OSConsumed : InheritableParamAttr {
   let Spellings = [Clang<"os_consumed">];
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 05703df2129f612..fa6f6acd0c30e88 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ 

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

2023-11-08 Thread Shengchen Kan via cfe-commits


@@ -131,35 +135,50 @@ bool X86TargetInfo::initFeatureMap(
   continue;
 }
 
-if (Feature.substr(0, 7) == "+avx10.") {
-  HasAVX10 = true;
-  HasAVX512F = true;
-  if (Feature.substr(Feature.size() - 3, 3) == "512") {
-HasEVEX512 = true;
-  } else if (Feature.substr(7, 2) == "1-") {
-HasEVEX512 = false;
+if (Feature.substr(1, 6) == "avx10.") {
+  if (Feature[0] == '+') {
+HasAVX10 = true;
+if (Feature.substr(Feature.size() - 3, 3) == "512")
+  HasAVX10_512 = true;
+LastAVX10 = Feature;
+  } else if (HasAVX10 && Feature == "-avx10.1-256") {
+HasAVX10 = false;
+HasAVX10_512 = false;
+  } else if (HasAVX10_512 && Feature == "-avx10.1-512") {
+HasAVX10_512 = false;
   }
+  // Postpone AVX10 features handling after AVX512 settled.
+  UpdatedAVX10FeaturesVec.push_back(Feature);
+  continue;
 } else if (!HasAVX512F && Feature.substr(0, 7) == "+avx512") {
   HasAVX512F = true;
+  LastAVX512 = Feature;
 } else if (HasAVX512F && Feature == "-avx512f") {
   HasAVX512F = false;
-} else if (HasAVX10 && Feature == "-avx10.1-256") {
-  HasAVX10 = false;
-  HasAVX512F = false;
-} else if (!HasEVEX512 && Feature == "+evex512") {
+} else if (HasEVEX512 != true && Feature == "+evex512") {

KanRobert wrote:

Comparing a int value with `true` and `false` may be confusing. I suggest 
"std::optional"

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


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

2023-11-08 Thread Shengchen Kan via cfe-commits


@@ -50,11 +50,11 @@ typedef __bf16 __m128bh __attribute__((__vector_size__(16), 
__aligned__(16)));
 
 /* Define the default attributes for the functions in this file. */
 #define __DEFAULT_FN_ATTRS 
\
-  __attribute__((__always_inline__, __nodebug__, __target__("sse2"),   
\
- __min_vector_width__(128)))
+  __attribute__((__always_inline__, __nodebug__,   
\
+ __target__("sse2,no-evex512"), __min_vector_width__(128)))
 #define __DEFAULT_FN_ATTRS_MMX 
\
-  __attribute__((__always_inline__, __nodebug__, __target__("mmx,sse2"),   
\
- __min_vector_width__(64)))
+  __attribute__((__always_inline__, __nodebug__,   
\

KanRobert wrote:

Why does the function targeted at sse2 need no-evex512?

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


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

2023-11-08 Thread Shengchen Kan via cfe-commits


@@ -15,8 +15,12 @@
 #define __AVX2INTRIN_H
 
 /* Define the default attributes for the functions in this file. */
-#define __DEFAULT_FN_ATTRS256 __attribute__((__always_inline__, __nodebug__, 
__target__("avx2"), __min_vector_width__(256)))
-#define __DEFAULT_FN_ATTRS128 __attribute__((__always_inline__, __nodebug__, 
__target__("avx2"), __min_vector_width__(128)))
+#define __DEFAULT_FN_ATTRS256  
\
+  __attribute__((__always_inline__, __nodebug__,   
\
+ __target__("avx2,no-evex512"), __min_vector_width__(256)))

KanRobert wrote:

Why does the function targeted at avx2 need `no-evex512`?

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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits

Bigcheese wrote:

Added test comments and added a test for `-Wsystem-headers` being present.

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


[clang] ExtractAPI: use zero-based indices for line/column in symbol graph (PR #71753)

2023-11-08 Thread via cfe-commits

QuietMisdreavus wrote:

An unfortunate side effect of changing the source location representation is 
that it required changing almost all the ExtractAPI tests.  But the overall 
diff is rather small.

cc @daniel-grumberg 

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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese updated 
https://github.com/llvm/llvm-project/pull/71612

>From 6c8c4cde5698a1693ad64a14a156030f249032a6 Mon Sep 17 00:00:00 2001
From: Michael Spencer 
Date: Tue, 7 Nov 2023 14:02:38 -1000
Subject: [PATCH 1/2] [clang][DependencyScanner] Remove all warning flags when
 suppressing warnings

Since system modules don't emit most warnings, remove the warning
flags to increase module reuse.
---
 .../DependencyScanningService.h   |  7 +-
 .../DependencyScanning/ModuleDepCollector.cpp | 26 ++
 .../ClangScanDeps/optimize-system-warnings.m  | 84 +++
 clang/tools/clang-scan-deps/ClangScanDeps.cpp |  1 +
 4 files changed, 116 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/ClangScanDeps/optimize-system-warnings.m

diff --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
index a4a03b88b205175..dcdf1c171f6d731 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
@@ -51,8 +51,11 @@ enum class ScanningOptimizations {
   /// Remove unused header search paths including header maps.
   HeaderSearch = 1,
 
-  LLVM_MARK_AS_BITMASK_ENUM(HeaderSearch),
-  All = HeaderSearch,
+  /// Remove warnings from system modules.
+  SystemWarnings = 2,
+
+  LLVM_MARK_AS_BITMASK_ENUM(SystemWarnings),
+  All = HeaderSearch | SystemWarnings,
   Default = All
 };
 
diff --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 5d95bb305bc38d8..9099c18391e4d29 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -52,6 +52,28 @@ static void optimizeHeaderSearchOpts(HeaderSearchOptions 
,
 Opts.UserEntries.push_back(Entries[Idx]);
 }
 
+static void optimizeDiagnosticOpts(DiagnosticOptions ,
+   bool IsSystemModule) {
+  // If this is not a system module or -Wsystem-headers was passed, don't
+  // optimize.
+  if (!IsSystemModule)
+return;
+  bool Wsystem_headers = false;
+  for (StringRef Opt : Opts.Warnings) {
+bool isPositive = !Opt.consume_front("no-");
+if (Opt == "system-headers")
+  Wsystem_headers = isPositive;
+  }
+  if (Wsystem_headers)
+return;
+
+  // Remove all warning flags. System modules suppress most, but not all,
+  // warnings.
+  Opts.Warnings.clear();
+  Opts.UndefPrefixes.clear();
+  Opts.Remarks.clear();
+}
+
 static std::vector splitString(std::string S, char Separator) {
   SmallVector Segments;
   StringRef(S).split(Segments, Separator, /*MaxSplit=*/-1, 
/*KeepEmpty=*/false);
@@ -532,6 +554,10 @@ ModuleDepCollectorPP::handleTopLevelModule(const Module 
*M) {
 if (any(MDC.OptimizeArgs & ScanningOptimizations::HeaderSearch))
   
optimizeHeaderSearchOpts(BuildInvocation.getMutHeaderSearchOpts(),
*MDC.ScanInstance.getASTReader(), *MF);
+if (any(MDC.OptimizeArgs & ScanningOptimizations::SystemWarnings))
+  optimizeDiagnosticOpts(
+  BuildInvocation.getMutDiagnosticOpts(),
+  BuildInvocation.getFrontendOpts().IsSystemModule);
   });
 
   MDC.associateWithContextHash(CI, MD);
diff --git a/clang/test/ClangScanDeps/optimize-system-warnings.m 
b/clang/test/ClangScanDeps/optimize-system-warnings.m
new file mode 100644
index 000..d61724c6f18fff8
--- /dev/null
+++ b/clang/test/ClangScanDeps/optimize-system-warnings.m
@@ -0,0 +1,84 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/build/compile-commands.json.in > 
%t/build/compile-commands.json
+// RUN: clang-scan-deps -compilation-database %t/build/compile-commands.json \
+// RUN:   -j 1 -format experimental-full -optimize-args=system-warnings > 
%t/deps.db
+// RUN: cat %t/deps.db | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "A"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "B"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK:]
+// 

[clang] ExtractAPI: use zero-based indices for line/column in symbol graph (PR #71753)

2023-11-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: QuietMisdreavus (QuietMisdreavus)


Changes

Other implementations of the symbol graph format use zero-based indices for 
source locations, which causes problems when combined with clang's current 
one-based indices. This commit sets ExtractAPI's symbol graph output to use 
zero-based indices to align with other implementations.

rdar://107639783

---

Patch is 67.53 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/71753.diff


52 Files Affected:

- (modified) clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
(+2-2) 
- (modified) clang/test/ExtractAPI/anonymous_record_no_typedef.c (+20-20) 
- (modified) clang/test/ExtractAPI/availability.c (+10-10) 
- (modified) clang/test/ExtractAPI/bool.c (+4-4) 
- (modified) clang/test/ExtractAPI/bool.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/class.cpp (+10-10) 
- (modified) clang/test/ExtractAPI/class_template.cpp (+2-2) 
- (modified) clang/test/ExtractAPI/class_template_param_inheritance.cpp (+2-2) 
- (modified) clang/test/ExtractAPI/class_template_partial_spec.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/class_template_spec.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/concept.cpp (+2-2) 
- (modified) clang/test/ExtractAPI/constructor_destructor.cpp (+6-6) 
- (modified) clang/test/ExtractAPI/conversions.cpp (+6-6) 
- (modified) clang/test/ExtractAPI/emit-symbol-graph/multi_file.c (+18-18) 
- (modified) clang/test/ExtractAPI/emit-symbol-graph/single_file.c (+6-6) 
- (modified) clang/test/ExtractAPI/enum.c (+38-38) 
- (modified) clang/test/ExtractAPI/field_template.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/function_noexcepts.cpp (+6-6) 
- (modified) clang/test/ExtractAPI/global_func_template.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/global_func_template_spec.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/global_record.c (+28-28) 
- (modified) clang/test/ExtractAPI/global_record_multifile.c (+28-28) 
- (modified) clang/test/ExtractAPI/global_var_template.cpp (+2-2) 
- (modified) clang/test/ExtractAPI/global_var_template_partial_spec.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/global_var_template_spec.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/known_files_only.c (+2-2) 
- (modified) clang/test/ExtractAPI/language.c (+4-4) 
- (modified) clang/test/ExtractAPI/macro_undefined.c (+6-6) 
- (modified) clang/test/ExtractAPI/macros.c (+12-12) 
- (modified) clang/test/ExtractAPI/method_template.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/method_template_spec.cpp (+6-6) 
- (modified) clang/test/ExtractAPI/methods.cpp (+10-10) 
- (modified) clang/test/ExtractAPI/multiple_inheritance.cpp (+8-8) 
- (modified) clang/test/ExtractAPI/namespace.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/nested_namespaces.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/objc_category.m (+8-8) 
- (modified) clang/test/ExtractAPI/objc_id_protocol.m (+8-8) 
- (modified) clang/test/ExtractAPI/objc_instancetype.m (+6-6) 
- (modified) clang/test/ExtractAPI/objc_interface.m (+14-14) 
- (modified) clang/test/ExtractAPI/objc_module_category.m (+16-16) 
- (modified) clang/test/ExtractAPI/objc_property.m (+16-16) 
- (modified) clang/test/ExtractAPI/objc_protocol.m (+4-4) 
- (modified) clang/test/ExtractAPI/objc_various_categories.m (+12-12) 
- (modified) clang/test/ExtractAPI/operator_overload.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/relative_include.m (+4-4) 
- (modified) clang/test/ExtractAPI/simple_inheritance.cpp (+4-4) 
- (modified) clang/test/ExtractAPI/struct.c (+18-18) 
- (modified) clang/test/ExtractAPI/typedef.c (+2-2) 
- (modified) clang/test/ExtractAPI/typedef_anonymous_record.c (+14-14) 
- (modified) clang/test/ExtractAPI/typedef_chain.c (+6-6) 
- (modified) clang/test/ExtractAPI/typedef_struct_enum.c (+12-12) 
- (modified) clang/test/ExtractAPI/underscored.c (+12-12) 


``diff
diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index 3c8668d26c60b76..1bc10b32322890e 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -109,8 +109,8 @@ Object serializeSourcePosition(const PresumedLoc ) {
   assert(Loc.isValid() && "invalid source position");
 
   Object SourcePosition;
-  SourcePosition["line"] = Loc.getLine();
-  SourcePosition["character"] = Loc.getColumn();
+  SourcePosition["line"] = Loc.getLine() - 1;
+  SourcePosition["character"] = Loc.getColumn() - 1;
 
   return SourcePosition;
 }
diff --git a/clang/test/ExtractAPI/anonymous_record_no_typedef.c 
b/clang/test/ExtractAPI/anonymous_record_no_typedef.c
index 0890e3cbdb6d085..0e50f4a0948c94a 100644
--- a/clang/test/ExtractAPI/anonymous_record_no_typedef.c
+++ b/clang/test/ExtractAPI/anonymous_record_no_typedef.c
@@ -105,12 +105,12 @@ struct Vehicle {
   {
 "range": {
   "end": {
-

[clang] ExtractAPI: use zero-based indices for line/column in symbol graph (PR #71753)

2023-11-08 Thread via cfe-commits

https://github.com/QuietMisdreavus created 
https://github.com/llvm/llvm-project/pull/71753

Other implementations of the symbol graph format use zero-based indices for 
source locations, which causes problems when combined with clang's current 
one-based indices. This commit sets ExtractAPI's symbol graph output to use 
zero-based indices to align with other implementations.

rdar://107639783

>From 7713e9fbb44c7a4bcfd9c76dc402bdfcd2c9a98f Mon Sep 17 00:00:00 2001
From: Victoria Mitchell 
Date: Wed, 8 Nov 2023 18:19:42 -0700
Subject: [PATCH] ExtractAPI: use zero-based indices for line/column in symbol
 graph

Other implementations of the symbol graph format use zero-based indices
for source locations, which causes problems when combined with clang's
current one-based indices. This commit sets ExtractAPI's symbol graph
output to use zero-based indices to align with other implementations.

rdar://107639783
---
 .../Serialization/SymbolGraphSerializer.cpp   |  4 +-
 .../ExtractAPI/anonymous_record_no_typedef.c  | 40 +-
 clang/test/ExtractAPI/availability.c  | 20 ++---
 clang/test/ExtractAPI/bool.c  |  8 +-
 clang/test/ExtractAPI/bool.cpp|  8 +-
 clang/test/ExtractAPI/class.cpp   | 20 ++---
 clang/test/ExtractAPI/class_template.cpp  |  4 +-
 .../class_template_param_inheritance.cpp  |  4 +-
 .../class_template_partial_spec.cpp   |  8 +-
 clang/test/ExtractAPI/class_template_spec.cpp |  8 +-
 clang/test/ExtractAPI/concept.cpp |  4 +-
 .../ExtractAPI/constructor_destructor.cpp | 12 +--
 clang/test/ExtractAPI/conversions.cpp | 12 +--
 .../ExtractAPI/emit-symbol-graph/multi_file.c | 36 -
 .../emit-symbol-graph/single_file.c   | 12 +--
 clang/test/ExtractAPI/enum.c  | 76 +--
 clang/test/ExtractAPI/field_template.cpp  |  8 +-
 clang/test/ExtractAPI/function_noexcepts.cpp  | 12 +--
 .../test/ExtractAPI/global_func_template.cpp  |  8 +-
 .../ExtractAPI/global_func_template_spec.cpp  |  8 +-
 clang/test/ExtractAPI/global_record.c | 56 +++---
 .../test/ExtractAPI/global_record_multifile.c | 56 +++---
 clang/test/ExtractAPI/global_var_template.cpp |  4 +-
 .../global_var_template_partial_spec.cpp  |  8 +-
 .../ExtractAPI/global_var_template_spec.cpp   |  8 +-
 clang/test/ExtractAPI/known_files_only.c  |  4 +-
 clang/test/ExtractAPI/language.c  |  8 +-
 clang/test/ExtractAPI/macro_undefined.c   | 12 +--
 clang/test/ExtractAPI/macros.c| 24 +++---
 clang/test/ExtractAPI/method_template.cpp |  8 +-
 .../test/ExtractAPI/method_template_spec.cpp  | 12 +--
 clang/test/ExtractAPI/methods.cpp | 20 ++---
 .../test/ExtractAPI/multiple_inheritance.cpp  | 16 ++--
 clang/test/ExtractAPI/namespace.cpp   |  8 +-
 clang/test/ExtractAPI/nested_namespaces.cpp   |  8 +-
 clang/test/ExtractAPI/objc_category.m | 16 ++--
 clang/test/ExtractAPI/objc_id_protocol.m  | 16 ++--
 clang/test/ExtractAPI/objc_instancetype.m | 12 +--
 clang/test/ExtractAPI/objc_interface.m| 28 +++
 clang/test/ExtractAPI/objc_module_category.m  | 32 
 clang/test/ExtractAPI/objc_property.m | 32 
 clang/test/ExtractAPI/objc_protocol.m |  8 +-
 .../test/ExtractAPI/objc_various_categories.m | 24 +++---
 clang/test/ExtractAPI/operator_overload.cpp   |  8 +-
 clang/test/ExtractAPI/relative_include.m  |  8 +-
 clang/test/ExtractAPI/simple_inheritance.cpp  |  8 +-
 clang/test/ExtractAPI/struct.c| 36 -
 clang/test/ExtractAPI/typedef.c   |  4 +-
 .../ExtractAPI/typedef_anonymous_record.c | 28 +++
 clang/test/ExtractAPI/typedef_chain.c | 12 +--
 clang/test/ExtractAPI/typedef_struct_enum.c   | 24 +++---
 clang/test/ExtractAPI/underscored.c   | 24 +++---
 52 files changed, 442 insertions(+), 442 deletions(-)

diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index 3c8668d26c60b76..1bc10b32322890e 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -109,8 +109,8 @@ Object serializeSourcePosition(const PresumedLoc ) {
   assert(Loc.isValid() && "invalid source position");
 
   Object SourcePosition;
-  SourcePosition["line"] = Loc.getLine();
-  SourcePosition["character"] = Loc.getColumn();
+  SourcePosition["line"] = Loc.getLine() - 1;
+  SourcePosition["character"] = Loc.getColumn() - 1;
 
   return SourcePosition;
 }
diff --git a/clang/test/ExtractAPI/anonymous_record_no_typedef.c 
b/clang/test/ExtractAPI/anonymous_record_no_typedef.c
index 0890e3cbdb6d085..0e50f4a0948c94a 100644
--- a/clang/test/ExtractAPI/anonymous_record_no_typedef.c
+++ b/clang/test/ExtractAPI/anonymous_record_no_typedef.c
@@ -105,12 +105,12 @@ struct Vehicle {
   {
  

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

2023-11-08 Thread Shengchen Kan via cfe-commits


@@ -119,9 +119,13 @@ bool X86TargetInfo::initFeatureMap(
 setFeatureEnabled(Features, F, true);
 
   std::vector UpdatedFeaturesVec;
-  bool HasEVEX512 = true;
+  std::vector UpdatedAVX10FeaturesVec;
+  int HasEVEX512 = -1;

KanRobert wrote:

Use std::optional ?

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


[clang] [MS-ABI] create unique vftable name for vftable defined with internal alias. (PR #71748)

2023-11-08 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

> Why are we creating a comdat here in the first place? 

I guess that's b2615aa4... but I'm pretty sure we fixed -fdata-sections so the 
backend automatically generates comdats.  So maybe we should just revert that.

> If we allow creating a comdat associated with an internal symbol, the backend 
> should handle it correctly; it's a bug if it crashes like you've described. 
> (I'm not sure how to reproduce the crash with your testcase, though.)

LangRef says "Because the name of the object must match the name of the COMDAT 
group, the linkage of the global object must not be local; local symbols can 
get renamed if a collision occurs in the symbol table."  I think that means the 
IR clang generates is illegal, but I guess nothing in the backend actually 
checks this.

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


[clang-tools-extra] [llvm] [clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Yeoul Na via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());
+  CharUnits Size = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  llvm::Constant *ElemSize =
+  llvm::ConstantInt::get(CountedByInst->getType(), Size.getQuantity());
+
+  llvm::Value *FAMSize = Builder.CreateMul(CountedByInst, ElemSize);

rapidsna wrote:

Hmm, it seems like `__bdos` returns `0` when it's pointing to an OOB object. 
https://godbolt.org/z/eT4c7aPWr
At least from what I'm seeing here. WDYT?


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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits

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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits


@@ -0,0 +1,84 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/build/compile-commands.json.in > 
%t/build/compile-commands.json
+// RUN: clang-scan-deps -compilation-database %t/build/compile-commands.json \
+// RUN:   -j 1 -format experimental-full -optimize-args=system-warnings > 
%t/deps.db
+// RUN: cat %t/deps.db | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "A"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "B"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK:]
+// CHECK:  }
+
+//--- build/compile-commands.json.in
+
+[
+{
+  "directory": "DIR",
+  "command": "clang -c DIR/A.m -isystem modules/A -I modules/B -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-module-maps",

Bigcheese wrote:

Ah, I missed the `-isystem`. It's verifying that both `-isystem` and `[system]` 
work.

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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits


@@ -0,0 +1,84 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/build/compile-commands.json.in > 
%t/build/compile-commands.json
+// RUN: clang-scan-deps -compilation-database %t/build/compile-commands.json \
+// RUN:   -j 1 -format experimental-full -optimize-args=system-warnings > 
%t/deps.db
+// RUN: cat %t/deps.db | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "A"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "B"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK:]
+// CHECK:  }
+
+//--- build/compile-commands.json.in
+
+[
+{
+  "directory": "DIR",
+  "command": "clang -c DIR/A.m -isystem modules/A -I modules/B -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-module-maps",

Bigcheese wrote:

Although I think I also misunderstood your question. Scanning both `A.m` and 
`B.m` verifies that the warning gets dropped and the hashes match due to there 
only being one module variant.

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


[clang] [MS-ABI] create unique vftable name for vftable defined with internal alias. (PR #71748)

2023-11-08 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

Why are we creating a comdat here in the first place?  Creating a comdat 
associated with an internal symbol doesn't do anything useful: an internal 
symbol can't be defined in any other translation unit, so the comdat will never 
be discarded.

If we allow creating a comdat associated with an internal symbol, the backend 
should handle it correctly; it's a bug if it crashes like you've described.  
(I'm not sure how to reproduce the crash with your testcase, though.)

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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits


@@ -0,0 +1,84 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/build/compile-commands.json.in > 
%t/build/compile-commands.json
+// RUN: clang-scan-deps -compilation-database %t/build/compile-commands.json \
+// RUN:   -j 1 -format experimental-full -optimize-args=system-warnings > 
%t/deps.db
+// RUN: cat %t/deps.db | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "A"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file":
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-W
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK:],
+// CHECK-NEXT:   "name": "B"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK:]
+// CHECK:  }
+
+//--- build/compile-commands.json.in
+
+[
+{
+  "directory": "DIR",
+  "command": "clang -c DIR/A.m -isystem modules/A -I modules/B -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-module-maps",

Bigcheese wrote:

I believe this was checking that context hash's matched, but we changed how 
those work so they no longer should. Module A can be removed.

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


[clang] [clang][DependencyScanner] Remove all warning flags when suppressing warnings (PR #71612)

2023-11-08 Thread Michael Spencer via cfe-commits


@@ -52,6 +52,28 @@ static void optimizeHeaderSearchOpts(HeaderSearchOptions 
,
 Opts.UserEntries.push_back(Entries[Idx]);
 }
 
+static void optimizeDiagnosticOpts(DiagnosticOptions ,
+   bool IsSystemModule) {
+  // If this is not a system module or -Wsystem-headers was passed, don't
+  // optimize.
+  if (!IsSystemModule)
+return;
+  bool Wsystem_headers = false;
+  for (StringRef Opt : Opts.Warnings) {
+bool isPositive = !Opt.consume_front("no-");
+if (Opt == "system-headers")
+  Wsystem_headers = isPositive;
+  }
+  if (Wsystem_headers)
+return;

Bigcheese wrote:

I don't really see a good way to reuse that, it's doing a bunch of other work 
on the `DiagnosticsEngine`, and the loop itself wants to process `no-` once and 
then check a bunch of different warning flags.

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


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

2023-11-08 Thread Louis Dionne via cfe-commits


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

ldionne wrote:

I think you probably want to add new tests in 
`clang/test/Driver/darwin-header-search-libcxx.cpp`. You also mentioned that 
other platforms (e.g. Linux?) handle search paths this way, right? Can you show 
where this is handled? They might have some tests you could take inspiration 
from?

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


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

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

5chmidti wrote:

> how about adding a function call like `f()`? will this can prevent clang 
> to emit empty function body?

Yep, thanks. I went this route, but I had to define a conversion operator to 
compile and keep the `<<` a `BinaryOperator`. The CI now passes

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


[openmp] [clang] [llvm] [OpenMP] Rework handling of global ctor/dtors in OpenMP (PR #71739)

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

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

>From 5e378ae3efdebedb044528167131c8cae4571a59 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 7 Nov 2023 17:12:31 -0600
Subject: [PATCH] [OpenMP] Rework handling of global ctor/dtors in OpenMP

Summary:
This patch reworks how we handle global constructors in OpenMP.
Previously, we emitted individual kernels that were all registered and
called individually. In order to provide more generic support, this
patch moves all handling of this to the target backend and the runtime
plugin. This has the benefit of supporting the GNU extensions for
constructors an destructors, removing a class of failures related to
shared library destruction order, and allows targets other than OpenMP
to use the same support without needing to change the frontend.

This is primarily done by calling kernels that the backend emits to
iterate a list of ctor / dtor functions. For x64, this is automatic and
we get it for free with the standard `dlopen` handling. For AMDGPU, we
emit `amdgcn.device.init` and `amdgcn.device.fini` functions which
handle everything atuomatically and simply need to be called. For NVPTX,
a patch https://github.com/llvm/llvm-project/pull/71549 provides the
kernels to call, but the runtime needs to set up the array manually by
pulling out all the known constructor / destructor functions.

One concession that this patch requires is the change that for GPU
targets in OpenMP offloading we will use `llvm.global_dtors` instead of
using `atexit`. This is because `atexit` is a separate runtime function
that does not mesh well with the handling we're trying to do here. This
should be equivalent in all cases except for cases where we would need
to destruct manually such as:

```
struct S { ~S() { foo(); } };
void foo() {
  static S s;
}
```

However this is broken in many other ways on the GPU, so it is not
regressing any support, simply increasing the scope of what we can
handle.

This changes the handling of ctors / dtors. This patch now outputs a
information message regarding the deprecation if the old format is used.
This will be completely removed in a later release.

Depends on: https://github.com/llvm/llvm-project/pull/71549
---
 clang/lib/CodeGen/CGDeclCXX.cpp   |  13 +-
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 130 --
 clang/lib/CodeGen/CGOpenMPRuntime.h   |   8 --
 clang/lib/CodeGen/CodeGenFunction.h   |   5 +
 clang/lib/CodeGen/CodeGenModule.h |  14 +-
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |   8 ++
 .../amdgcn_openmp_device_math_constexpr.cpp   |  48 +--
 .../amdgcn_target_global_constructor.cpp  |  30 ++--
 clang/test/OpenMP/declare_target_codegen.cpp  |   1 -
 ...x_declare_target_var_ctor_dtor_codegen.cpp |  35 +
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |   4 -
 llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp |   7 +-
 .../plugins-nextgen/amdgpu/src/rtl.cpp|  52 +++
 .../common/PluginInterface/GlobalHandler.h|  10 +-
 .../PluginInterface/PluginInterface.cpp   |   7 +
 .../common/PluginInterface/PluginInterface.h  |  14 ++
 .../plugins-nextgen/cuda/src/rtl.cpp  | 115 
 openmp/libomptarget/src/rtl.cpp   |   6 +
 18 files changed, 291 insertions(+), 216 deletions(-)

diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index 3fa28b343663f61..e08a1e5f42df20c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -327,6 +327,15 @@ void CodeGenFunction::registerGlobalDtorWithAtExit(const 
VarDecl ,
   registerGlobalDtorWithAtExit(dtorStub);
 }
 
+/// Register a global destructor using the LLVM 'llvm.global_dtors' global.
+void CodeGenFunction::registerGlobalDtorWithLLVM(const VarDecl ,
+ llvm::FunctionCallee Dtor,
+ llvm::Constant *Addr) {
+  // Create a function which calls the destructor.
+  llvm::Function *dtorStub = createAtExitStub(VD, Dtor, Addr);
+  CGM.AddGlobalDtor(dtorStub);
+}
+
 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
   // extern "C" int atexit(void (*f)(void));
   assert(dtorStub->getType() ==
@@ -519,10 +528,6 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl 
*D,
D->hasAttr()))
 return;
 
-  if (getLangOpts().OpenMP &&
-  getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit))
-return;
-
   // Check if we've already initialized this decl.
   auto I = DelayedCXXInitPosition.find(D);
   if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index a8e1150e44566b8..d2be8141a3a4b31 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1747,136 +1747,6 @@ llvm::Function 

[clang] [llvm] [PowerPC][X86] Make cpu id builtins target independent and lower for PPC (PR #68919)

2023-11-08 Thread Eli Friedman via cfe-commits


@@ -359,6 +359,13 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
   bool isSPRegName(StringRef RegName) const override {
 return RegName.equals("r1") || RegName.equals("x1");
   }
+
+  // We support __builtin_cpu_supports/__builtin_cpu_is on targets that

efriedma-quic wrote:

Musl targets are supposed to use a "musl" triple.  We already have 
Triple::isMusl(). If it's somehow possible for both isOSGlibc() and isMusl() to 
be true, I'd consider that a bug in isOSGlibc().

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


[clang] [MS-ABI] create unique vftable name for vftable defined with internal alias. (PR #71748)

2023-11-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: None (jyu2-git)


Changes

We got a error:
LLVM ERROR: Associative COMDAT symbol '??_7?$T@Vlambda_06B@' is not a key for its COMDAT
Current we create internal alias for vftable when lambd is used.
For the test, IR generate:
 $"??_7?$T@Vlambda_0@@$0A@@@6b@" = comdat any

@0 = private unnamed_addr constant { [2 x ptr] } { [2 x ptr] [ptr 
@"??_R4?$T@Vlambda_0@@$0A@@@6b@", ptr @"?c@b@@UEAAXXZ"] }, comdat($"??_7?$T@Vlambda_0@@$0A@@@6b@")

@"??_7?$T@Vlambda_0@@$0A@@@6b@" = internal unnamed_addr 
alias ptr, getelementptr inbounds ({ [2 x ptr] }, ptr @0, i32 0, i32 0, 
i32 1)

According LLVM language reference manual section on COMDATs:
There are some restrictions on the properties of the global object. It,
or an alias to it, must have the same name as the COMDAT group when
targeting COFF. The contents and size of this object may be used during
link-time to determine which COMDAT groups get selected depending on the
selection kind. Because the name of the object must match the name of the
COMDAT group, the linkage of the global object must not be local; local
symbols can get renamed if a collision occurs in the symbol table.

So one way to fix this is to generate unqiue virtual function table name, to 
aviod local symbol renaming.
The fix is to generate unqiue vftable name for every TU where encoded file name 
in addition.

after the change:
lambda_A7884B04_0
before:
lambda_0


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


6 Files Affected:

- (modified) clang/include/clang/AST/Mangle.h (+2-1) 
- (modified) clang/lib/AST/MicrosoftMangle.cpp (+14-2) 
- (modified) clang/lib/CodeGen/CGCall.cpp (+3) 
- (modified) clang/lib/CodeGen/MicrosoftCXXABI.cpp (+10-5) 
- (modified) clang/test/CodeGen/windows-seh-EHa-TryInFinally.cpp (+23) 
- (added) clang/test/CodeGenCXX/ms-local-vft-alias-comdat.cpp (+31) 


``diff
diff --git a/clang/include/clang/AST/Mangle.h b/clang/include/clang/AST/Mangle.h
index e586b0cec43dfd6..420ba52f255eb2c 100644
--- a/clang/include/clang/AST/Mangle.h
+++ b/clang/include/clang/AST/Mangle.h
@@ -239,7 +239,8 @@ class MicrosoftMangleContext : public MangleContext {
   /// them correctly.
   virtual void mangleCXXVFTable(const CXXRecordDecl *Derived,
 ArrayRef BasePath,
-raw_ostream ) = 0;
+raw_ostream ,
+bool IsLocalVFTAliasReq = false) = 0;
 
   /// Mangle vbtable symbols.  Only a subset of the bases along the path
   /// to the vbtable are included in the name.  It's up to the caller to pick
diff --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index 50ab6ea59be9d03..a84959b3680fdde 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -148,6 +148,7 @@ class MicrosoftMangleContextImpl : public 
MicrosoftMangleContext {
   llvm::DenseMap SEHFilterIds;
   llvm::DenseMap SEHFinallyIds;
   SmallString<16> AnonymousNamespaceHash;
+  bool IsLocalVFTAliasReq = false;
 
 public:
   MicrosoftMangleContextImpl(ASTContext , DiagnosticsEngine ,
@@ -165,7 +166,8 @@ class MicrosoftMangleContextImpl : public 
MicrosoftMangleContext {
   raw_ostream &) override;
   void mangleCXXVFTable(const CXXRecordDecl *Derived,
 ArrayRef BasePath,
-raw_ostream ) override;
+raw_ostream ,
+bool IsLocalVFTAliaesReq = false) override;
   void mangleCXXVBTable(const CXXRecordDecl *Derived,
 ArrayRef BasePath,
 raw_ostream ) override;
@@ -211,6 +213,10 @@ class MicrosoftMangleContextImpl : public 
MicrosoftMangleContext {
   void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
  raw_ostream ) override;
   void mangleStringLiteral(const StringLiteral *SL, raw_ostream ) override;
+  void setIsLocalVFTAliasReq(bool isLocalVFTAliasReq) {
+IsLocalVFTAliasReq = isLocalVFTAliasReq;
+  }
+  bool getIsLocalVFTAliasReq() { return IsLocalVFTAliasReq; }
   bool getNextDiscriminator(const NamedDecl *ND, unsigned ) {
 const DeclContext *DC = getEffectiveDeclContext(ND);
 if (!DC->isFunctionOrMethod())
@@ -1106,6 +1112,10 @@ void 
MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
   if (const CXXRecordDecl *Record = dyn_cast(TD)) {
 if (Record->isLambda()) {
   llvm::SmallString<10> Name("getLambdaContextDecl();
   unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
@@ -3634,11 +3644,12 @@ void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
 
 void MicrosoftMangleContextImpl::mangleCXXVFTable(
 const CXXRecordDecl *Derived, ArrayRef BasePath,
-raw_ostream ) {
+raw_ostream , bool IsLocalVFTAliasReq) {
   //  ::= ?_7  
   // [] @
   // NOTE:  here is 

[clang] [MS-ABI] create unique vftable name for vftable defined with internal alias. (PR #71748)

2023-11-08 Thread via cfe-commits

https://github.com/jyu2-git created 
https://github.com/llvm/llvm-project/pull/71748

We got a error:
LLVM ERROR: Associative COMDAT symbol '??_7?$T@V6B@' is not a key 
for its COMDAT
Current we create internal alias for vftable when lambd is used.
For the test, IR generate:
 $"??_7?$T@V@@$0A@@@6b@" = comdat any

@0 = private unnamed_addr constant { [2 x ptr] } { [2 x ptr] [ptr 
@"??_R4?$T@V@@$0A@@@6b@", ptr @"?c@b@@UEAAXXZ"] }, 
comdat($"??_7?$T@V@@$0A@@@6b@")

@"??_7?$T@V@@$0A@@@6b@" = internal unnamed_addr alias ptr, 
getelementptr inbounds ({ [2 x ptr] }, ptr @0, i32 0, i32 0, i32 1)

According LLVM language reference manual section on COMDATs:
There are some restrictions on the properties of the global object. It,
or an alias to it, must have the same name as the COMDAT group when
targeting COFF. The contents and size of this object may be used during
link-time to determine which COMDAT groups get selected depending on the
selection kind. Because the name of the object must match the name of the
COMDAT group, the linkage of the global object must not be local; local
symbols can get renamed if a collision occurs in the symbol table.

So one way to fix this is to generate unqiue virtual function table name, to 
aviod local symbol renaming.
The fix is to generate unqiue vftable name for every TU where encoded file name 
in addition.

after the change:

before:



>From 3313aca0622da3882a9e5bf304b89f28fecce7fe Mon Sep 17 00:00:00 2001
From: Jennifer Yu 
Date: Mon, 6 Nov 2023 20:51:39 -0800
Subject: [PATCH 1/2] [SEH] Fix assertin when return scalar value from __try
 block.

Current compler assert with `!SI->isAtomic() && !SI->isVolatile()' failed

This due to following rule:
First, no exception can move in or out of _try region., i.e., no "potential
faulty instruction can be moved across _try boundary.
Second, the order of exceptions for instructions 'directly' under a _try
must be preserved (not applied to those in callees).
Finally, global states (local/global/heap variables) that can be read
outside of _try region must be updated in memory (not just in register)
before the subsequent exception occurs.

All memory instructions inside a _try are considered as 'volatile' to assure
2nd and 3rd rules for C-code above. This is a little sub-optimized. But it's
acceptable as the amount of code directly under _try is very small.
However during findDominatingStoreToReturnValue: those are not allowed.

To fix just skip the assertion when current function has seh try.
---
 clang/lib/CodeGen/CGCall.cpp  |  3 +++
 .../CodeGen/windows-seh-EHa-TryInFinally.cpp  | 23 +++
 2 files changed, 26 insertions(+)

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e7951b3a3f4d855..bc367b89992bbd9 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3507,6 +3507,9 @@ static llvm::StoreInst 
*findDominatingStoreToReturnValue(CodeGenFunction ) {
   return nullptr;
 // These aren't actually possible for non-coerced returns, and we
 // only care about non-coerced returns on this code path.
+// All memory instructions inside __try block are volatile.
+if (CGF.currentFunctionUsesSEHTry() && SI->isVolatile())
+  return SI;
 assert(!SI->isAtomic() && !SI->isVolatile());
 return SI;
   };
diff --git a/clang/test/CodeGen/windows-seh-EHa-TryInFinally.cpp 
b/clang/test/CodeGen/windows-seh-EHa-TryInFinally.cpp
index fab567e763df443..ce2a9528e1908a9 100644
--- a/clang/test/CodeGen/windows-seh-EHa-TryInFinally.cpp
+++ b/clang/test/CodeGen/windows-seh-EHa-TryInFinally.cpp
@@ -67,3 +67,26 @@ void foo()
 }
   }
 }
+
+// CHECK-LABEL:@"?bar@@YAHXZ"()
+// CHECK: invoke.cont:
+// CHECK: invoke void @llvm.seh.try.begin()
+// CHECK: invoke.cont1:
+// CHECK: store volatile i32 1, ptr %cleanup.dest.slot
+// CHECK: invoke void @llvm.seh.try.end()
+// CHECK: invoke.cont2:
+// CHECK: call void @"?fin$0@0@bar@@"
+// CHECK: %cleanup.dest3 = load i32, ptr %cleanup.dest.slot
+// CHECK: return:
+// CHECK: ret i32 11
+int bar()
+{
+  int x;
+  __try {
+return 11;
+  } __finally {
+if (_abnormal_termination()) {
+  x = 9;
+}
+  }
+}

>From 52981cb76b510593c7b20bafc0d65a756b1ccd32 Mon Sep 17 00:00:00 2001
From: Jennifer Yu 
Date: Tue, 7 Nov 2023 10:05:41 -0800
Subject: [PATCH 2/2] [MSABI] create unique vftable name for vftable defined
 with internal alias.

We got a error:
LLVM ERROR: Associative COMDAT symbol '??_7?$T@V6B@' is not a key 
for its COMDAT

Current we create internal alias for vftable when lambd is used.
For the test, IR generate:

$"??_7?$T@V@@$0A@@@6b@" = comdat any

@0 = private unnamed_addr constant { [2 x ptr] } { [2 x ptr] [ptr 
@"??_R4?$T@V@@$0A@@@6b@", ptr @"?c@b@@UEAAXXZ"] }, 
comdat($"??_7?$T@V@@$0A@@@6b@")

@"??_7?$T@V@@$0A@@@6b@" = internal unnamed_addr alias ptr, 
getelementptr inbounds ({ [2 x ptr] }, ptr @0, i32 0, i32 0, i32 1)

According LLVM language reference manual 

[clang-tools-extra] [clang] [llvm] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Bill Wendling via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());
+  CharUnits Size = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  llvm::Constant *ElemSize =
+  llvm::ConstantInt::get(CountedByInst->getType(), Size.getQuantity());
+
+  llvm::Value *FAMSize = Builder.CreateMul(CountedByInst, ElemSize);

bwendling wrote:

Okay. I converted the instructions to carry the signedness of the `counted_by` 
field's type. PTAL.

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


[lldb] [clang] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70639)

2023-11-08 Thread Michael Buch via cfe-commits

Michael137 wrote:

> This causes Clang to assert:
> 
> ```
>   llvm/lib/IR/Metadata.cpp:689:
>   void llvm::MDNode::resolve(): Assertion `isUniqued() && "Expected this 
> to be uniqued"' failed.
> ```
> 
> See https://bugs.chromium.org/p/chromium/issues/detail?id=1500262#c1 for a 
> reproducer.
> 
> I'll revert to green.

Thanks for the repro. Reduced it to:
```
struct Foo; 
template  using Int = int;  
class Bar { 
  template  static const bool Constant = false; 
  Int> Val;   
  Bar();
};  
Bar::Bar() {}   
```
when compiling with `-debug-info-kind=limited`.

The issue was that `EmitGlobalVariable` can cause creation of `DINodes`, which, 
if using limited debug-info, will be temporary. But the emission of the global 
variables is done *after* we've uniqued the temporaries. So the fix is really 
to just do the `EmitGlobalVariable` at the beginning of 
`CGDebugInfo::finalize`. Will submit a new PR with that change and a new 
test-case for this

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


[llvm] [clang] [libc++][hardening] Fix references to old names for hardening modes (PR #71743)

2023-11-08 Thread Konstantin Varlamov via cfe-commits

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


[clang] 4a9c71b - [libc++][hardening] Fix references to old names for hardening modes (#71743)

2023-11-08 Thread via cfe-commits

Author: Konstantin Varlamov
Date: 2023-11-08T13:16:01-10:00
New Revision: 4a9c71b8c2d01bf4efacf488d46ed2d92e71f355

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

LOG: [libc++][hardening] Fix references to old names for hardening modes 
(#71743)

This should fix some builds broken by
https://github.com/llvm/llvm-project/pull/70575

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake
clang/cmake/caches/Fuchsia.cmake
llvm/cmake/modules/HandleLLVMOptions.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index a4d2926559eee7f..4b9085d99378c6f 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -81,7 +81,7 @@ if(APPLE)
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")
   set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
   set(RUNTIMES_CMAKE_ARGS 
"-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13;-DCMAKE_OSX_ARCHITECTURES=arm64|x86_64" 
CACHE STRING "")
 endif()

diff  --git a/clang/cmake/caches/Fuchsia.cmake 
b/clang/cmake/caches/Fuchsia.cmake
index 4c9cd12101d478a..dad434be720da11 100644
--- a/clang/cmake/caches/Fuchsia.cmake
+++ b/clang/cmake/caches/Fuchsia.cmake
@@ -116,7 +116,7 @@ else()
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")
   set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
   set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE 
STRING "")
   set(RUNTIMES_CMAKE_ARGS 
"-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13;-DCMAKE_OSX_ARCHITECTURES=arm64|x86_64" 
CACHE STRING "")

diff  --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index ca7cedd6e4afff4..6a3c49edc912ded 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -111,12 +111,12 @@ if( LLVM_ENABLE_ASSERTIONS )
   endif()
   # Enable assertions in libstdc++.
   add_compile_definitions(_GLIBCXX_ASSERTIONS)
-  # Cautiously enable the safe hardened mode in libc++.
+  # Cautiously enable the extensive hardening mode in libc++.
   if((DEFINED LIBCXX_HARDENING_MODE) AND
- (NOT LIBCXX_HARDENING_MODE STREQUAL "safe"))
-message(WARNING "LLVM_ENABLE_ASSERTIONS implies LIBCXX_HARDENING_MODE 
\"safe\" but is overriden from command line with value 
\"${LIBCXX_HARDENING_MODE}\".")
+ (NOT LIBCXX_HARDENING_MODE STREQUAL "extensive"))
+message(WARNING "LLVM_ENABLE_ASSERTIONS implies LIBCXX_HARDENING_MODE 
\"extensive\" but is overriden from command line with value 
\"${LIBCXX_HARDENING_MODE}\".")
   else()
-set(LIBCXX_HARDENING_MODE "safe")
+set(LIBCXX_HARDENING_MODE "extensive")
   endif()
 endif()
 



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


[clang] [llvm] [libc++][hardening] Fix references to old names for hardening modes (PR #71743)

2023-11-08 Thread Louis Dionne via cfe-commits

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


[clang] [clang][CodeGen] Ensure consistent `mustprogress` attribute emission across all paths (PR #71452)

2023-11-08 Thread Eli Friedman via cfe-commits


@@ -1482,6 +1477,11 @@ void CodeGenFunction::GenerateCode(GlobalDecl GD, 
llvm::Function *Fn,
   } else
 llvm_unreachable("no definition for emitted function");
 
+  // This is checked after emitting the function body so we know if there
+  // are any permitted infinite loops.

efriedma-quic wrote:

No, I mean, there isn't a reason to specifically do it *after* emitting the 
function body, as opposed to before we emit it (when we compute most other 
attributes).

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


[clang] [llvm] [libc++][hardening] Fix references to old names for hardening modes (PR #71743)

2023-11-08 Thread Louis Dionne via cfe-commits


@@ -116,7 +116,7 @@ else()
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")

ldionne wrote:

@petrhosek Can we set up a Fuchsia build bot? We even have one for Android now!

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


[clang] [llvm] [libc++][hardening] Fix references to old names for hardening modes (PR #71743)

2023-11-08 Thread Louis Dionne via cfe-commits

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


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


[clang] [llvm] [libc++][hardening] Fix references to old names for hardening modes (PR #71743)

2023-11-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Konstantin Varlamov (var-const)


Changes

This should fix some builds broken by 
https://github.com/llvm/llvm-project/pull/70575


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


3 Files Affected:

- (modified) clang/cmake/caches/Fuchsia-stage2.cmake (+1-1) 
- (modified) clang/cmake/caches/Fuchsia.cmake (+1-1) 
- (modified) llvm/cmake/modules/HandleLLVMOptions.cmake (+4-4) 


``diff
diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index a4d2926559eee7f..4b9085d99378c6f 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -81,7 +81,7 @@ if(APPLE)
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")
   set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
   set(RUNTIMES_CMAKE_ARGS 
"-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13;-DCMAKE_OSX_ARCHITECTURES=arm64|x86_64" 
CACHE STRING "")
 endif()
diff --git a/clang/cmake/caches/Fuchsia.cmake b/clang/cmake/caches/Fuchsia.cmake
index 4c9cd12101d478a..dad434be720da11 100644
--- a/clang/cmake/caches/Fuchsia.cmake
+++ b/clang/cmake/caches/Fuchsia.cmake
@@ -116,7 +116,7 @@ else()
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")
   set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
   set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE 
STRING "")
   set(RUNTIMES_CMAKE_ARGS 
"-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13;-DCMAKE_OSX_ARCHITECTURES=arm64|x86_64" 
CACHE STRING "")
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index ca7cedd6e4afff4..6a3c49edc912ded 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -111,12 +111,12 @@ if( LLVM_ENABLE_ASSERTIONS )
   endif()
   # Enable assertions in libstdc++.
   add_compile_definitions(_GLIBCXX_ASSERTIONS)
-  # Cautiously enable the safe hardened mode in libc++.
+  # Cautiously enable the extensive hardening mode in libc++.
   if((DEFINED LIBCXX_HARDENING_MODE) AND
- (NOT LIBCXX_HARDENING_MODE STREQUAL "safe"))
-message(WARNING "LLVM_ENABLE_ASSERTIONS implies LIBCXX_HARDENING_MODE 
\"safe\" but is overriden from command line with value 
\"${LIBCXX_HARDENING_MODE}\".")
+ (NOT LIBCXX_HARDENING_MODE STREQUAL "extensive"))
+message(WARNING "LLVM_ENABLE_ASSERTIONS implies LIBCXX_HARDENING_MODE 
\"extensive\" but is overriden from command line with value 
\"${LIBCXX_HARDENING_MODE}\".")
   else()
-set(LIBCXX_HARDENING_MODE "safe")
+set(LIBCXX_HARDENING_MODE "extensive")
   endif()
 endif()
 

``




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


[clang] [clang-tools-extra] [llvm] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Bill Wendling via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());

bwendling wrote:

There's a sema error check to ensure that it's applied only to a FAM. I suppose 
it can't hurt to add an assert though.

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


[clang] [llvm] [libc++][hardening] Fix references to old names for hardening modes (PR #71743)

2023-11-08 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const created 
https://github.com/llvm/llvm-project/pull/71743

This should fix some builds broken by 
https://github.com/llvm/llvm-project/pull/70575


>From 11dad502fa66c6f7d0377a554c7f22ef21a9faee Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Wed, 8 Nov 2023 13:12:38 -1000
Subject: [PATCH] [libc++][hardening] Fix references to old names for hardening
 modes

This should fix some builds broken by 
https://github.com/llvm/llvm-project/pull/70575
---
 clang/cmake/caches/Fuchsia-stage2.cmake| 2 +-
 clang/cmake/caches/Fuchsia.cmake   | 2 +-
 llvm/cmake/modules/HandleLLVMOptions.cmake | 8 
 3 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index a4d2926559eee7f..4b9085d99378c6f 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -81,7 +81,7 @@ if(APPLE)
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")
   set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
   set(RUNTIMES_CMAKE_ARGS 
"-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13;-DCMAKE_OSX_ARCHITECTURES=arm64|x86_64" 
CACHE STRING "")
 endif()
diff --git a/clang/cmake/caches/Fuchsia.cmake b/clang/cmake/caches/Fuchsia.cmake
index 4c9cd12101d478a..dad434be720da11 100644
--- a/clang/cmake/caches/Fuchsia.cmake
+++ b/clang/cmake/caches/Fuchsia.cmake
@@ -116,7 +116,7 @@ else()
   set(LIBCXX_ABI_VERSION 2 CACHE STRING "")
   set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
-  set(LIBCXX_HARDENING_MODE "unchecked" CACHE STRING "")
+  set(LIBCXX_HARDENING_MODE "none" CACHE STRING "")
   set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
   set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE 
STRING "")
   set(RUNTIMES_CMAKE_ARGS 
"-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13;-DCMAKE_OSX_ARCHITECTURES=arm64|x86_64" 
CACHE STRING "")
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index ca7cedd6e4afff4..6a3c49edc912ded 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -111,12 +111,12 @@ if( LLVM_ENABLE_ASSERTIONS )
   endif()
   # Enable assertions in libstdc++.
   add_compile_definitions(_GLIBCXX_ASSERTIONS)
-  # Cautiously enable the safe hardened mode in libc++.
+  # Cautiously enable the extensive hardening mode in libc++.
   if((DEFINED LIBCXX_HARDENING_MODE) AND
- (NOT LIBCXX_HARDENING_MODE STREQUAL "safe"))
-message(WARNING "LLVM_ENABLE_ASSERTIONS implies LIBCXX_HARDENING_MODE 
\"safe\" but is overriden from command line with value 
\"${LIBCXX_HARDENING_MODE}\".")
+ (NOT LIBCXX_HARDENING_MODE STREQUAL "extensive"))
+message(WARNING "LLVM_ENABLE_ASSERTIONS implies LIBCXX_HARDENING_MODE 
\"extensive\" but is overriden from command line with value 
\"${LIBCXX_HARDENING_MODE}\".")
   else()
-set(LIBCXX_HARDENING_MODE "safe")
+set(LIBCXX_HARDENING_MODE "extensive")
   endif()
 endif()
 

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


[clang] [clang-tools-extra] [llvm] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Bill Wendling via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());
+  CharUnits Size = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  llvm::Constant *ElemSize =
+  llvm::ConstantInt::get(CountedByInst->getType(), Size.getQuantity());
+
+  llvm::Value *FAMSize = Builder.CreateMul(CountedByInst, ElemSize);

bwendling wrote:

Hmm...I think maybe I should put a check in to see if the types are signed and 
then perform the appropriate `[SU]Ext` operations... Thoughts?

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


[clang] [clang-tools-extra] [llvm] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Bill Wendling via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());
+  CharUnits Size = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  llvm::Constant *ElemSize =
+  llvm::ConstantInt::get(CountedByInst->getType(), Size.getQuantity());
+
+  llvm::Value *FAMSize = Builder.CreateMul(CountedByInst, ElemSize);

bwendling wrote:

That's more a sanitizer check, which should abort. This code is just dealing 
with the __bdos calls. If it returns a negative value, then that's badness. I 
know that it can return `-1` (if the second argument is `1`, otherwise `0`) if 
it can't determine the size of the object. I don't know if it's completely 
invalid, per se. For instance, if you have this:

```
struct s {
  char count;
  int fam[];
};
```

And you want `>128` 

[clang] [clang-tools-extra] [llvm] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-11-08 Thread Yeoul Na via cfe-commits


@@ -859,53 +860,93 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of a pointer into the flexible array:
+//
+// __builtin_dynamic_object_size(>array[42], 1) ==
+// (p->count - 42) * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//max(sizeof(struct s),
+//offsetof(struct s, array) + p->count * sizeof(*p->array))
+//
 const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
+const Expr *Idx = nullptr;
+if (const auto *UO = dyn_cast(Base);
+UO && UO->getOpcode() == UO_AddrOf) {
+  if (const auto *ASE = dyn_cast(UO->getSubExpr())) {
+Base = ASE->getBase();
+Idx = ASE->getIdx()->IgnoreParenImpCasts();
+if (const auto *IL = dyn_cast(Idx);
+IL && !IL->getValue().getZExtValue()) {
+  Idx = nullptr;
+}
   }
+}
 
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
-  unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
+if (const ValueDecl *CountedByFD = FindCountedByField(Base)) {
+  const RecordDecl *OuterRD =
+  CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  ASTContext  = getContext();
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Load the counted_by field.
+  const Expr *CountedByExpr = BuildCountedByFieldExpr(Base, CountedByFD);
+  llvm::Value *CountedByInst =
+  EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  if (Idx) {
+llvm::Value *IdxInst = EmitAnyExprToTemp(Idx).getScalarVal();
+IdxInst = Builder.CreateZExtOrTrunc(IdxInst, CountedByInst->getType());
+CountedByInst = Builder.CreateSub(CountedByInst, IdxInst);
+  }
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  // Get the size of the flexible array member's base type.
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(Ctx, OuterRD);
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FAM->getType());

rapidsna wrote:

I see. So sounds like this relies on the fact that counted_by can currently be 
added to a flexible array member only? Should we add an assertion here to make 
it easier to deal with when that assumption breaks in future?

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


[clang] [openmp] [OpenMP] Add support for Solaris/x86_64 (PR #70593)

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


@@ -70,6 +72,15 @@ struct kmp_sys_timer {
   struct timespec start;
 };
 
+#ifdef KMP_OS_SOLARIS
+// Convert timeval to timespec.
+#define TIMEVAL_TO_TIMESPEC(tv, ts)
\

shiltian wrote:

It looks like this macro is not guarded correct somewhere else such that the 
compiler complains on a non-Solaris system.
```
[19/128] Building CXX object runtime/src/CMakeFiles/omp.dir/z_Linux_util.cpp.o
/home/ac.shilei.tian/Documents/vscode/llvm-project/openmp/runtime/src/z_Linux_util.cpp:77:9:
 warning: 'TIMEVAL_TO_TIMESPEC' macro redefined [-Wmacro-redefined]
   77 | #define TIMEVAL_TO_TIMESPEC(tv, ts) 
   \
  | ^
/usr/include/sys/time.h:38:10: note: previous definition is here
   38 | # define TIMEVAL_TO_TIMESPEC(tv, ts) {  
 \
  |  ^
```

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


  1   2   3   4   5   >