[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

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

Thank you for the patch!

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,11 @@
+// RUN: cp %s %t.c

HighCommander4 wrote:

I think it would be more consistent with the rest of the clangd subproject if 
this was expressed as a unit test.

It can take the form of a new section added to [this existing 
test](https://searchfox.org/llvm/rev/6a91b7051df7e108c8ffd79c084859f90559962d/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp#19),
 similar to [this 
section](https://searchfox.org/llvm/rev/6a91b7051df7e108c8ffd79c084859f90559962d/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp#61-66)
 but using `EXPECT_UNAVAILABLE` (since the refactoring does not end up being 
available on this test case, even though it passes this particular check). The 
`[[ ]]` in the input source code annotates the source range on which the 
refactoring is invoked.

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits


@@ -176,7 +176,8 @@ bool ExtractionContext::exprIsValidOutside(const 
clang::Stmt *Scope) const {
   SourceLocation ScopeBegin = Scope->getBeginLoc();
   SourceLocation ScopeEnd = Scope->getEndLoc();
   for (const Decl *ReferencedDecl : ReferencedDecls) {
-if (SM.isPointWithin(ReferencedDecl->getBeginLoc(), ScopeBegin, ScopeEnd) 
&&
+if (ReferencedDecl->getBeginLoc().isValid() &&

HighCommander4 wrote:

(I wondered whether there might be other cases where a `Decl` has an invalid 
location where we'd want this function to return `false`, but I couldn't think 
of a specific case, so I think this is fine for the time being.)

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


[llvm] [clang] [llvm][ARM] Emit MVE .arch_extension after .fpu directive if it does not include MVE features (PR #71545)

2023-11-10 Thread David Spickett via cfe-commits


@@ -0,0 +1,56 @@
+; REQUIRES: arm-registered-target
+; RUN: %clang --target=arm-none-eabi -mcpu=cortex-m85 -mfloat-abi=hard 
-save-temps=obj -S -o - %s | FileCheck %s
+; RUN: %clang --target=arm-none-eabi -mcpu=cortex-m55 -mfloat-abi=hard 
-save-temps=obj -S -o - %s | FileCheck %s
+; RUN: %clang --target=arm-none-eabi -mcpu=cortex-m85 -mfloat-abi=hard -O2 -c 
-mthumb -save-temps=obj %s
+; RUN: %clang --target=arm-none-eabi -mcpu=cortex-m55 -mfloat-abi=hard -O2 -c 
-mthumb -save-temps=obj %s
+; CHECK: .fpu   fpv5-d16
+; CHECK  .arch_extension mve.fp
+target datalayout = "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64"
+target triple = "thumbv8.1m.main-none-unknown-eabihf"
+
+%struct.dummy_t = type { float, float, float, float }
+
+define dso_local signext i8 @foo(ptr noundef %handle) #0 {
+entry:
+  %handle.addr = alloca ptr, align 4
+  store ptr %handle, ptr %handle.addr, align 4
+  %0 = load ptr, ptr %handle.addr, align 4
+  %a = getelementptr inbounds %struct.dummy_t, ptr %0, i32 0, i32 0
+  %1 = load float, ptr %a, align 4
+  %sub = fsub float 0x3F5439DE4000, %1
+  %2 = load ptr, ptr %handle.addr, align 4
+  %a1 = getelementptr inbounds %struct.dummy_t, ptr %2, i32 0, i32 0
+  %3 = load float, ptr %a1, align 4
+  %4 = call float @llvm.fmuladd.f32(float 0x3F847AE14000, float %sub, 
float %3)
+  store float %4, ptr %a1, align 4
+  %5 = load ptr, ptr %handle.addr, align 4
+  %b = getelementptr inbounds %struct.dummy_t, ptr %5, i32 0, i32 1
+  %6 = load float, ptr %b, align 4
+  %sub2 = fsub float 0x3F5439DE4000, %6
+  %7 = load ptr, ptr %handle.addr, align 4
+  %b3 = getelementptr inbounds %struct.dummy_t, ptr %7, i32 0, i32 1
+  %8 = load float, ptr %b3, align 4
+  %9 = call float @llvm.fmuladd.f32(float 0x3F947AE14000, float %sub2, 
float %8)
+  store float %9, ptr %b3, align 4
+  %10 = load ptr, ptr %handle.addr, align 4
+  %c = getelementptr inbounds %struct.dummy_t, ptr %10, i32 0, i32 2
+  %11 = load float, ptr %c, align 4
+  %sub4 = fsub float 0x3F5439DE4000, %11
+  %12 = load ptr, ptr %handle.addr, align 4
+  %c5 = getelementptr inbounds %struct.dummy_t, ptr %12, i32 0, i32 2
+  %13 = load float, ptr %c5, align 4
+  %14 = call float @llvm.fmuladd.f32(float 0x3F9EB851E000, float %sub4, 
float %13)
+  store float %14, ptr %c5, align 4
+  %15 = load ptr, ptr %handle.addr, align 4
+  %d = getelementptr inbounds %struct.dummy_t, ptr %15, i32 0, i32 3
+  %16 = load float, ptr %d, align 4
+  %sub6 = fsub float 0x3F5439DE4000, %16
+  %17 = load ptr, ptr %handle.addr, align 4
+  %d7 = getelementptr inbounds %struct.dummy_t, ptr %17, i32 0, i32 3
+  %18 = load float, ptr %d7, align 4
+  %19 = call float @llvm.fmuladd.f32(float 0x3FA47AE14000, float %sub6, 
float %18)
+  store float %19, ptr %d7, align 4
+  ret i8 0

DavidSpickett wrote:

Ok I see, you need to setup the call to this fmuladd, that you know will emit 
MVE instructions.

In that case, could you add a check line for one of the MVE instructions as 
well? That would make the intent clearer, and warn us in the (unlikely) case 
that this code stopped emitting MVE instructions.

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


[llvm] [clang] [llvm][ARM] Emit MVE .arch_extension after .fpu directive if it does not include MVE features (PR #71545)

2023-11-10 Thread David Spickett via cfe-commits

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


[clang-tools-extra] 0255b21 - [clangd] Add tweak for turning an unscoped into a scoped enum (#69481)

2023-11-10 Thread via cfe-commits

Author: ckandeler
Date: 2023-11-10T10:02:05+01:00
New Revision: 0255b217c3766ce0aa23bd4fb050b447be2a1d26

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

LOG: [clangd] Add tweak for turning an unscoped into a scoped enum (#69481)

Added: 
clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp
clang-tools-extra/clangd/unittests/tweaks/ScopifyEnumTests.cpp

Modified: 
clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
clang-tools-extra/clangd/unittests/CMakeLists.txt
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 526a073f619ea34..2e948c23569f686 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -27,6 +27,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   PopulateSwitch.cpp
   RawStringLiteral.cpp
   RemoveUsingNamespace.cpp
+  ScopifyEnum.cpp
   SpecialMembers.cpp
   SwapIfBranches.cpp
 

diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp
new file mode 100644
index 000..357af8c9b679a99
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp
@@ -0,0 +1,222 @@
+//===--- ScopifyEnum.cpp --- -*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ParsedAST.h"
+#include "XRefs.h"
+#include "refactor/Tweak.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
+
+#include 
+
+namespace clang::clangd {
+namespace {
+
+/// Turns an unscoped into a scoped enum type.
+/// Before:
+///   enum E { EV1, EV2 };
+///^
+///   void f() { E e1 = EV1; }
+///
+/// After:
+///   enum class E { EV1, EV2 };
+///   void f() { E e1 = E::EV1; }
+///
+/// Note that the respective project code might not compile anymore
+/// if it made use of the now-gone implicit conversion to int.
+/// This is out of scope for this tweak.
+///
+/// TODO: In the above example, we could detect that the values
+///   start with the enum name, and remove that prefix.
+
+class ScopifyEnum : public Tweak {
+  const char *id() const final;
+  std::string title() const override { return "Convert to scoped enum"; }
+  llvm::StringLiteral kind() const override {
+return CodeAction::REFACTOR_KIND;
+  }
+  bool prepare(const Selection &Inputs) override;
+  Expected apply(const Selection &Inputs) override;
+
+  using MakeReplacement =
+  std::function;
+  llvm::Error addClassKeywordToDeclarations();
+  llvm::Error scopifyEnumValues();
+  llvm::Error scopifyEnumValue(const EnumConstantDecl &CD, StringRef Prefix);
+  llvm::Expected getContentForFile(StringRef FilePath);
+  unsigned getOffsetFromPosition(const Position &Pos, StringRef Content) const;
+  llvm::Error addReplacementForReference(const ReferencesResult::Reference 
&Ref,
+ const MakeReplacement 
&GetReplacement);
+  llvm::Error addReplacement(StringRef FilePath, StringRef Content,
+ const tooling::Replacement &Replacement);
+  Position getPosition(const Decl &D) const;
+
+  const EnumDecl *D = nullptr;
+  const Selection *S = nullptr;
+  SourceManager *SM = nullptr;
+  llvm::SmallVector> ExtraBuffers;
+  llvm::StringMap ContentPerFile;
+  Effect E;
+};
+
+REGISTER_TWEAK(ScopifyEnum)
+
+bool ScopifyEnum::prepare(const Selection &Inputs) {
+  if (!Inputs.AST->getLangOpts().CPlusPlus11)
+return false;
+  const SelectionTree::Node *N = Inputs.ASTSelection.commonAncestor();
+  if (!N)
+return false;
+  D = N->ASTNode.get();
+  return D && !D->isScoped() && D->isThisDeclarationADefinition();
+}
+
+Expected ScopifyEnum::apply(const Selection &Inputs) {
+  S = &Inputs;
+  SM = &S->AST->getSourceManager();
+  E.FormatEdits = false;
+  ContentPerFile.insert(std::make_pair(SM->getFilename(D->getLocation()),
+   
SM->getBufferData(SM->getMainFileID(;
+
+  if (auto Err = addClassKeywordToDeclarations())
+return Err;
+  if (auto Err = scopifyEnumValues())
+return Err;
+
+  return E;
+}
+
+llvm::Error ScopifyEnum::addClassKeywordToDeclarations() {
+  for (const auto &Ref :
+   findReferences(*S->AST, getPosition(*D), 0, S->Index, false)
+   .Referenc

[clang-tools-extra] [clangd] Add tweak for turning an unscoped into a scoped enum (PR #69481)

2023-11-10 Thread via cfe-commits

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


[clang-tools-extra] [clangd] Add tweak for turning an unscoped into a scoped enum (PR #69481)

2023-11-10 Thread via cfe-commits

ckandeler wrote:

Merged as per the review here: https://github.com/llvm/llvm-project/pull/67645

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


[clang] cc75e52 - [clang-format][NFC] Refactor isPointerOrReference

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

Author: Owen Pan
Date: 2023-11-10T01:23:05-08:00
New Revision: cc75e520162ef651977d3f6d11b0d0b92dd2be07

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

LOG: [clang-format][NFC] Refactor isPointerOrReference

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/WhitespaceManager.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 87f6a76ec5bfd39..14a3c21ba44eaee 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -692,6 +692,10 @@ struct FormatToken {
 TT_LeadingJavaAnnotation);
   }
 
+  bool isPointerOrReference() const {
+return isOneOf(tok::star, tok::amp, tok::ampamp);
+  }
+
   bool isUnaryOperator() const {
 switch (Tok.getKind()) {
 case tok::plus:

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 77586532c851ff2..7167e50ec724eab 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -380,7 +380,7 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
 
   // For left qualifiers preceeded by nothing, a template declaration, or 
*,&,&&
   // we only perform sorting.
-  if (!TypeToken || TypeToken->isOneOf(tok::star, tok::amp, tok::ampamp) ||
+  if (!TypeToken || TypeToken->isPointerOrReference() ||
   TypeToken->ClosesRequiresClause || TypeToken->ClosesTemplateDeclaration) 
{
 
 // Don't sort past a non-configured qualifier token.

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 729e7e370bf62ea..d648e441f23fe9e 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -405,7 +405,7 @@ class AnnotatingParser {
 // void (^ObjCBlock)(void);
 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
 bool ProbablyFunctionType =
-CurrentToken->isOneOf(tok::star, tok::amp, tok::ampamp, tok::caret);
+CurrentToken->isPointerOrReference() || CurrentToken->is(tok::caret);
 bool HasMultipleLines = false;
 bool HasMultipleParametersOnALine = false;
 bool MightBeObjCForRangeLoop =
@@ -422,8 +422,7 @@ class AnnotatingParser {
   FormatToken *PrevPrev = Prev->getPreviousNonComment();
   FormatToken *Next = CurrentToken->Next;
   if (PrevPrev && PrevPrev->is(tok::identifier) &&
-  PrevPrev->isNot(TT_TypeName) &&
-  Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
+  PrevPrev->isNot(TT_TypeName) && Prev->isPointerOrReference() &&
   CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
 Prev->setType(TT_BinaryOperator);
 LookForDecls = false;
@@ -460,10 +459,8 @@ class AnnotatingParser {
   //   auto my_lambda = MACRO((Type *type, int i) { .. body .. });
   for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken;
Tok = Tok->Next) {
-if (Tok->is(TT_BinaryOperator) &&
-Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) {
+if (Tok->is(TT_BinaryOperator) && Tok->isPointerOrReference())
   Tok->setType(TT_PointerOrReference);
-}
   }
 }
 
@@ -1861,8 +1858,8 @@ class AnnotatingParser {
   if (Previous->opensScope())
 break;
   if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
-  Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
-  Previous->Previous && Previous->Previous->isNot(tok::equal)) {
+  Previous->isPointerOrReference() && Previous->Previous &&
+  Previous->Previous->isNot(tok::equal)) {
 Previous->setType(TT_PointerOrReference);
   }
 }
@@ -2023,7 +2020,7 @@ class AnnotatingParser {
 } else if (isDeductionGuide(Current)) {
   // Deduction guides trailing arrow " A(...) -> A;".
   Current.setType(TT_TrailingReturnArrow);
-} else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
+} else if (Current.isPointerOrReference()) {
   Current.setType(determineStarAmpUsage(
   Current,
   Contexts.back().CanBeExpression && Contexts.back().IsExpression,
@@ -3281,7 +3278,7 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken &Current,
 continue;
   }
   if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) &&
-  Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) 
{
+  Next->Next && Next->Next->isPointerOrReference()) {
 // For operato

[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-11-10 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,187 @@
+//===-- CodeSnippetHighlighter.cpp - Code snippet highlighting --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Frontend/CodeSnippetHighlighter.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+using namespace clang;
+
+static constexpr raw_ostream::Colors CommentColor = raw_ostream::GREEN;
+static constexpr raw_ostream::Colors LiteralColor = raw_ostream::CYAN;
+static constexpr raw_ostream::Colors KeywordColor = raw_ostream::BLUE;
+
+llvm::SmallVector CodeSnippetHighlighter::highlightLine(
+unsigned LineNumber, const Preprocessor *PP, const LangOptions &LangOpts,
+FileID FID, const SourceManager &SM, const char *LineStart) {
+  std::chrono::steady_clock::time_point begin =
+  std::chrono::steady_clock::now();
+
+  if (!PP)
+return {};
+
+  // Might cause emission of another diagnostic.
+  if (PP->getIdentifierTable().getExternalIdentifierLookup())
+return {};
+
+  size_t NTokens = 0;
+  // Classify the given token and append it to the given vector.
+  auto appendStyle = [PP, &LangOpts](llvm::SmallVector &Vec,
+ const Token &T, unsigned Start,
+ unsigned Length) -> void {
+if (T.is(tok::raw_identifier)) {
+  StringRef RawIdent = T.getRawIdentifier();
+  // Special case true/false/nullptr literals, since they will otherwise be
+  // treated as keywords.
+  if (RawIdent == "true" || RawIdent == "false" || RawIdent == "nullptr") {
+Vec.push_back(StyleRange{Start, Start + Length, LiteralColor});
+  } else {
+const IdentifierInfo *II = PP->getIdentifierInfo(RawIdent);
+assert(II);
+if (II->isKeyword(LangOpts))
+  Vec.push_back(StyleRange{Start, Start + Length, KeywordColor});
+  }
+} else if (tok::isLiteral(T.getKind())) {
+  Vec.push_back(StyleRange{Start, Start + Length, LiteralColor});
+} else {
+  assert(T.is(tok::comment));
+  Vec.push_back(StyleRange{Start, Start + Length, CommentColor});
+}
+  };
+
+  // Figure out where to start lexing from.
+  auto Buff = SM.getBufferOrNone(FID);
+  assert(Buff);
+  Lexer L = Lexer(FID, *Buff, SM, LangOpts);
+  L.SetKeepWhitespaceMode(true);
+
+  // Seek to the last save point before the start of the line.
+  if (const char *Save = PP->getSaveFor(LineStart);
+  Buff->getBufferStart() <= Save && Save < Buff->getBufferEnd()) {
+size_t Offset = Save - Buff->getBufferStart();
+assert(Save >= Buff->getBufferStart());
+assert(Save <= Buff->getBufferEnd());
+
+L.seek(Offset, /*IsAtStartOfLine=*/true);
+  }
+
+  llvm::SmallVector LineRanges;
+  bool Stop = false;
+  while (!Stop) {
+++NTokens;
+Token T;
+Stop = L.LexFromRawLexer(T);
+if (T.is(tok::unknown))
+  continue;
+
+// We are only interested in identifiers, literals and comments.
+if (!T.is(tok::raw_identifier) && !T.is(tok::comment) &&
+!tok::isLiteral(T.getKind()))
+  continue;
+
+bool Invalid = false;
+unsigned EndLine = SM.getSpellingLineNumber(T.getEndLoc(), &Invalid) - 1;
+if (Invalid)
+  continue;
+
+if (EndLine < LineNumber)
+  continue;
+unsigned StartLine =
+SM.getSpellingLineNumber(T.getLocation(), &Invalid) - 1;
+if (Invalid)
+  continue;
+if (StartLine > LineNumber)
+  break;
+
+// Must have an intersection at this point
+assert(StartLine <= LineNumber && EndLine >= LineNumber);
+
+unsigned StartCol =
+SM.getSpellingColumnNumber(T.getLocation(), &Invalid) - 1;
+if (Invalid)
+  continue;
+
+// Simple tokens.
+if (StartLine == EndLine) {
+  appendStyle(LineRanges, T, StartCol, T.getLength());
+  continue;
+}
+unsigned NumLines = EndLine - StartLine;
+assert(NumLines >= 1);
+
+// For tokens that span multiple lines (think multiline comments), we
+// divide them into multiple StyleRanges.
+unsigned EndCol = SM.getSpellingColum

[clang] [analyzer] Move security.cert.env.InvalidPtr out of alpha (PR #71912)

2023-11-10 Thread Endre Fülöp via cfe-commits

https://github.com/gamesh411 created 
https://github.com/llvm/llvm-project/pull/71912

Thanks to recent improvements in #67663, InvalidPtr checker does not emit any 
false positives on the following OS projects: memcached, tmux, curl, twin, vim, 
openssl, sqlite, ffmpeg, postgres, tinyxml2, libwebm, xerces, bitcoin, 
protobuf, qtbase, contour, acid, openrct2.

From 2d94271affd27c5ebf1073a9effbe6c7815f5c01 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Fri, 10 Nov 2023 10:08:58 +0100
Subject: [PATCH] [analyzer] Move security.cert.env.InvalidPtr out of alpha

Thanks to recent improvements in #67663, InvalidPtr checker does
not emit any false positives on the following OS projects:
memcached, tmux, curl, twin, vim, openssl, sqlite, ffmpeg, postgres,
tinyxml2, libwebm, xerces, bitcoin, protobuf, qtbase, contour, acid,
openrct2
---
 clang/docs/analyzer/checkers.rst  | 138 +-
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  28 ++--
 clang/test/Analysis/analyzer-config.c |   2 +-
 clang/test/Analysis/cert/env31-c.c|  10 +-
 .../Analysis/cert/env34-c-cert-examples.c |  10 +-
 clang/test/Analysis/cert/env34-c.c|   4 +-
 clang/test/Analysis/invalid-ptr-checker.c |   8 +-
 7 files changed, 101 insertions(+), 99 deletions(-)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 43137f4b020f9f7..ff4559aa89d96a0 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -755,6 +755,75 @@ security
 
 Security related checkers.
 
+.. _security-cert-env-InvalidPtr:
+
+security.cert.env.InvalidPtr
+""
+
+Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
+
+ENV31-C:
+Rule is about the possible problem with `main` function's third argument, 
environment pointer,
+"envp". When environment array is modified using some modification function
+such as putenv, setenv or others, It may happen that memory is reallocated,
+however "envp" is not updated to reflect the changes and points to old memory
+region.
+
+ENV34-C:
+Some functions return a pointer to a statically allocated buffer.
+Consequently, subsequent call of these functions will invalidate previous
+pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
+
+.. code-block:: c
+
+  int main(int argc, const char *argv[], const char *envp[]) {
+if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
+  // setenv call may invalidate 'envp'
+  /* Handle error */
+}
+if (envp != NULL) {
+  for (size_t i = 0; envp[i] != NULL; ++i) {
+puts(envp[i]);
+// envp may no longer point to the current environment
+// this program has unanticipated behavior, since envp
+// does not reflect changes made by setenv function.
+  }
+}
+return 0;
+  }
+
+  void previous_call_invalidation() {
+char *p, *pp;
+
+p = getenv("VAR");
+setenv("SOMEVAR", "VALUE", /*overwrite = */1);
+// call to 'setenv' may invalidate p
+
+*p;
+// dereferencing invalid pointer
+  }
+
+
+The ``InvalidatingGetEnv`` option is available for treating getenv calls as
+invalidating. When enabled, the checker issues a warning if getenv is called
+multiple times and their results are used without first creating a copy.
+This level of strictness might be considered overly pedantic for the commonly
+used getenv implementations.
+
+To enable this option, use:
+``-analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
+
+By default, this option is set to *false*.
+
+When this option is enabled, warnings will be generated for scenarios like the
+following:
+
+.. code-block:: c
+
+  char* p = getenv("VAR");
+  char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
+  strlen(p); // warns about accessing invalid ptr
+
 .. _security-FloatLoopCounter:
 
 security.FloatLoopCounter (C)
@@ -2479,75 +2548,6 @@ alpha.security.cert.env
 
 SEI CERT checkers of `Environment C coding rules 
`_.
 
-.. _alpha-security-cert-env-InvalidPtr:
-
-alpha.security.cert.env.InvalidPtr
-""
-
-Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
-
-ENV31-C:
-Rule is about the possible problem with `main` function's third argument, 
environment pointer,
-"envp". When environment array is modified using some modification function
-such as putenv, setenv or others, It may happen that memory is reallocated,
-however "envp" is not updated to reflect the changes and points to old memory
-region.
-
-ENV34-C:
-Some functions return a pointer to a statically allocated buffer.
-Consequently, subsequent call of these functions will invalidate previous
-pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
-
-.. code-block:: c
-
-  int main(int argc, const char *argv[], const char *envp[]) {
-if (setenv("MY_NEW_VAR", "new_value", 1) != 

[clang] [analyzer] Move security.cert.env.InvalidPtr out of alpha (PR #71912)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Endre Fülöp (gamesh411)


Changes

Thanks to recent improvements in #67663, InvalidPtr checker does not 
emit any false positives on the following OS projects: memcached, tmux, curl, 
twin, vim, openssl, sqlite, ffmpeg, postgres, tinyxml2, libwebm, xerces, 
bitcoin, protobuf, qtbase, contour, acid, openrct2.

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


7 Files Affected:

- (modified) clang/docs/analyzer/checkers.rst (+69-69) 
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (+15-13) 
- (modified) clang/test/Analysis/analyzer-config.c (+1-1) 
- (modified) clang/test/Analysis/cert/env31-c.c (+5-5) 
- (modified) clang/test/Analysis/cert/env34-c-cert-examples.c (+5-5) 
- (modified) clang/test/Analysis/cert/env34-c.c (+2-2) 
- (modified) clang/test/Analysis/invalid-ptr-checker.c (+4-4) 


``diff
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 43137f4b020f9f7..ff4559aa89d96a0 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -755,6 +755,75 @@ security
 
 Security related checkers.
 
+.. _security-cert-env-InvalidPtr:
+
+security.cert.env.InvalidPtr
+""
+
+Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
+
+ENV31-C:
+Rule is about the possible problem with `main` function's third argument, 
environment pointer,
+"envp". When environment array is modified using some modification function
+such as putenv, setenv or others, It may happen that memory is reallocated,
+however "envp" is not updated to reflect the changes and points to old memory
+region.
+
+ENV34-C:
+Some functions return a pointer to a statically allocated buffer.
+Consequently, subsequent call of these functions will invalidate previous
+pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
+
+.. code-block:: c
+
+  int main(int argc, const char *argv[], const char *envp[]) {
+if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
+  // setenv call may invalidate 'envp'
+  /* Handle error */
+}
+if (envp != NULL) {
+  for (size_t i = 0; envp[i] != NULL; ++i) {
+puts(envp[i]);
+// envp may no longer point to the current environment
+// this program has unanticipated behavior, since envp
+// does not reflect changes made by setenv function.
+  }
+}
+return 0;
+  }
+
+  void previous_call_invalidation() {
+char *p, *pp;
+
+p = getenv("VAR");
+setenv("SOMEVAR", "VALUE", /*overwrite = */1);
+// call to 'setenv' may invalidate p
+
+*p;
+// dereferencing invalid pointer
+  }
+
+
+The ``InvalidatingGetEnv`` option is available for treating getenv calls as
+invalidating. When enabled, the checker issues a warning if getenv is called
+multiple times and their results are used without first creating a copy.
+This level of strictness might be considered overly pedantic for the commonly
+used getenv implementations.
+
+To enable this option, use:
+``-analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
+
+By default, this option is set to *false*.
+
+When this option is enabled, warnings will be generated for scenarios like the
+following:
+
+.. code-block:: c
+
+  char* p = getenv("VAR");
+  char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
+  strlen(p); // warns about accessing invalid ptr
+
 .. _security-FloatLoopCounter:
 
 security.FloatLoopCounter (C)
@@ -2479,75 +2548,6 @@ alpha.security.cert.env
 
 SEI CERT checkers of `Environment C coding rules 
`_.
 
-.. _alpha-security-cert-env-InvalidPtr:
-
-alpha.security.cert.env.InvalidPtr
-""
-
-Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
-
-ENV31-C:
-Rule is about the possible problem with `main` function's third argument, 
environment pointer,
-"envp". When environment array is modified using some modification function
-such as putenv, setenv or others, It may happen that memory is reallocated,
-however "envp" is not updated to reflect the changes and points to old memory
-region.
-
-ENV34-C:
-Some functions return a pointer to a statically allocated buffer.
-Consequently, subsequent call of these functions will invalidate previous
-pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
-
-.. code-block:: c
-
-  int main(int argc, const char *argv[], const char *envp[]) {
-if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
-  // setenv call may invalidate 'envp'
-  /* Handle error */
-}
-if (envp != NULL) {
-  for (size_t i = 0; envp[i] != NULL; ++i) {
-puts(envp[i]);
-// envp may no longer point to the current environment
-// this program has unanticipated behavior, since envp
-// does not reflect changes made by setenv function.
-  }
-}
-return 0;

[clang] f7bbb58 - Reland "[clang-format] Handle variable declarations in BreakAfterAttributes (#71755)"

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

Author: Owen Pan
Date: 2023-11-10T01:53:43-08:00
New Revision: f7bbb58690910a8320b0927525dfba19df69a910

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

LOG: Reland "[clang-format] Handle variable declarations in 
BreakAfterAttributes (#71755)"

Also fixed another bug in isStartOfName().

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 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 d648e441f23fe9e..9499b3f31623c4f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1997,6 +1997,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = &Current;
   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
@@ -2181,8 +2185,10 @@ class AnnotatingParser {
 if (Style.isVerilog())
   return false;
 
-if (Tok.isNot(tok::identifier) || !Tok.Previous)
+if (Tok.isNot(tok::identifier) || !Tok.Previous || !Tok.Next ||
+Tok.Next->isPointerOrReference()) {
   return false;
+}
 
 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
  

[clang] [analyzer] Move security.cert.env.InvalidPtr out of alpha (PR #71912)

2023-11-10 Thread via cfe-commits

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

LGTM. The test results sound convincing and this is just a checker-rename 
commit that doesn't contain "actual" code changes that could've introduced bugs.

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


[clang] 86ef9d3 - Revert "[clang-format] Handle variable declarations in BreakAfterAttributes (#71755)"

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

Author: Owen Pan
Date: 2023-11-10T02:03:35-08:00
New Revision: 86ef9d36519f72c06741335ce0a445ab73eb4cfb

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

LOG: Revert "[clang-format] Handle variable declarations in 
BreakAfterAttributes (#71755)"

This reverts commit f7bbb58690910a8320b0927525dfba19df69a910 which caused
another formatting failure in polly.

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index d496fc85f7ae71a..21342e1b89ea866 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 variable/function
-  (including constructor/destructor) declaration/definition name.
+  Break after a group of C++11 attributes before a function
+  declaration/definition name.
 
   Possible values:
 
@@ -2059,10 +2059,6 @@ 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]]
@@ -2073,9 +2069,6 @@ 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();
@@ -2085,8 +2078,6 @@ 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 9442344000e142b..3e9d1915badd87f 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1428,10 +1428,6 @@ 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]]
@@ -1440,9 +1436,6 @@ 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();
@@ -1450,16 +1443,14 @@ 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 variable/function
-  /// (including constructor/destructor) declaration/definition name.
+  /// Break after a group of C++11 attributes before a function
+  /// declaration/definition name.
   /// \version 16
   AttributeBreakingStyle BreakAfterAttributes;
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9499b3f31623c4f..d648e441f23fe9e 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1997,10 +1997,6 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = &Current;
   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
@@ -2185,10 +2181,8 @@ class AnnotatingParser {
 if (Style.isVerilog())
   return false;
 
-if (Tok.isNot(tok::identifier) || !Tok.Previous || !Tok.Next ||
-Tok.Next->isPointerOrReference()) {
+if (Tok.isNot(tok::identifier) || !Tok.Previous)
   return false;
-}
 
 if (Tok.Previous->isOneOf(TT_L

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";

ilg-ul wrote:

Done.

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] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

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


@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Check for the folder where the executable is located, if different.

ilg-ul wrote:

Done.

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] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-10 Thread Liviu Ionescu 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)

ilg-ul wrote:

Done.

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] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-10 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 49fd28d9601dde429436655ec74234e895c60b89 
31b7482ffabda61c005a4cd90a07bcfec65c232e -- 
clang/lib/Driver/ToolChains/Darwin.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index d89b6d60f185..fa10400d8922 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2472,7 +2472,8 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
   case ToolChain::CST_Libcxx: {
 // On Darwin, libc++ can be installed in one of the following places:
 // 1. Alongside the compiler in /include/c++/v1
-// 2. Alongside the compiler in 
/../include/c++/v1
+// 2. Alongside the compiler in
+// /../include/c++/v1
 // 3. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
 // The precedence of paths is as listed above, i.e. we take the first path

``




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


[flang] [clang] [flang][driver] add -flang-deprecated-no-hlfir hidden option (PR #71820)

2023-11-10 Thread Tom Eccles via cfe-commits

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

> Thanks for the review @tblah. I could not find 
> flang/test/HLFIR/hlfir-flang.f90 test, did you mean 
> flang/test/HLFIR/hlfir-**flags**.f90 (in which case it is updated in this PR 
> already).

Yes I meant hlfir-flags.f90. Sorry about that. Thanks for the changes!

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


[PATCH] D138846: MC/DC in LLVM Source-Based Code Coverage: LLVM back-end and compiler-rt

2023-11-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Just a heads up that we're seeing crashes in the Rust compiler which bisects to 
this change. Investigating in 
https://bugs.chromium.org/p/chromium/issues/detail?id=1500558


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138846

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


[clang] 7b1a058 - [clang][Interp][NFC] Use direct Get{Local,Global} when possible

2023-11-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-11-10T11:30:38+01:00
New Revision: 7b1a0580216796045b880251e031a1e5e0ecad74

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

LOG: [clang][Interp][NFC] Use direct Get{Local,Global} when possible

When returning variable declaration values, try to get the value
directly instead of always going through a Pointer.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index a2cf682b2532bde..15a717089660337 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2119,27 +2119,33 @@ bool ByteCodeExprGen::visitDecl(const VarDecl 
*VD) {
   if (!this->visitVarDecl(VD))
 return false;
 
+  std::optional VarT = classify(VD->getType());
   // Get a pointer to the variable
   if (Context::shouldBeGloballyIndexed(VD)) {
 auto GlobalIndex = P.getGlobal(VD);
 assert(GlobalIndex); // visitVarDecl() didn't return false.
-if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
-  return false;
+if (VarT) {
+  if (!this->emitGetGlobal(*VarT, *GlobalIndex, VD))
+return false;
+} else {
+  if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
+return false;
+}
   } else {
 auto Local = Locals.find(VD);
 assert(Local != Locals.end()); // Same here.
-if (!this->emitGetPtrLocal(Local->second.Offset, VD))
-  return false;
+if (VarT) {
+  if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
+return false;
+} else {
+  if (!this->emitGetPtrLocal(Local->second.Offset, VD))
+return false;
+}
   }
 
   // Return the value
-  if (std::optional VarT = classify(VD->getType())) {
-if (!this->emitLoadPop(*VarT, VD))
-  return false;
-
+  if (VarT)
 return this->emitRet(*VarT, VD);
-  }
-
   return this->emitRetValue(VD);
 }
 



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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Björn Pettersson via cfe-commits


@@ -0,0 +1,11 @@
+// RUN: cp %s %t.c

bjope wrote:

I've been trying to do that, but so far no luck. I hit this assertion in 
TweakTesting.h:
`  assert(!A.points().empty() || !A.ranges().empty()); 
`

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


[clang] [clang][Interp] Diagnose reads from non-const global variables (PR #71919)

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

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/71919

This fixes a long-standing FIXME item.

Unfortunately it changes the diagnostic output of the tests added in 
`cxx23.cpp`, but they were wrong before and are wrong after, so no big deal.

>From bc71936279a1c669a8fb23c98d880063bd3f6ddb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 9 Nov 2023 15:45:05 +0100
Subject: [PATCH] [clang][Interp] Diagnose reads from non-const global
 variables

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  2 +-
 clang/lib/AST/Interp/Interp.cpp  | 44 ++--
 clang/lib/AST/Interp/Interp.h| 14 
 clang/lib/AST/Interp/Opcodes.td  |  1 +
 clang/test/AST/Interp/arrays.cpp | 32 +
 clang/test/AST/Interp/cxx23.cpp  | 25 +-
 clang/test/AST/Interp/literals.cpp   | 27 +--
 7 files changed, 122 insertions(+), 23 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 15a717089660337..eca31efc85272bf 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2125,7 +2125,7 @@ bool ByteCodeExprGen::visitDecl(const VarDecl 
*VD) {
 auto GlobalIndex = P.getGlobal(VD);
 assert(GlobalIndex); // visitVarDecl() didn't return false.
 if (VarT) {
-  if (!this->emitGetGlobal(*VarT, *GlobalIndex, VD))
+  if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
 return false;
 } else {
   if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 144b674451e353c..d1d812a591591bf 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -53,6 +53,18 @@ static bool Jf(InterpState &S, CodePtr &PC, int32_t Offset) {
   return true;
 }
 
+static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
+ const ValueDecl *VD) {
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
+  S.FFDiag(Loc,
+   VD->getType()->isIntegralOrEnumerationType()
+   ? diag::note_constexpr_ltor_non_const_int
+   : diag::note_constexpr_ltor_non_constexpr,
+   1)
+  << VD;
+  S.Note(VD->getLocation(), diag::note_declared_at);
+}
+
 static bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
 AccessKinds AK) {
   if (Ptr.isActive())
@@ -170,9 +182,7 @@ bool CheckExtern(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
 
   if (!S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus) {
 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
-S.Note(VD->getLocation(), diag::note_declared_at);
+diagnoseNonConstVariable(S, OpPC, VD);
   }
   return false;
 }
@@ -215,6 +225,24 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr,
   return true;
 }
 
+bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc) {
+  assert(Desc);
+  if (const auto *D = Desc->asValueDecl()) {
+if (const auto *VD = dyn_cast(D);
+VD && VD->hasGlobalStorage() &&
+!(VD->isConstexpr() || VD->getType().isConstQualified())) {
+  diagnoseNonConstVariable(S, OpPC, VD);
+  return false;
+}
+  }
+
+  return true;
+}
+
+static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  return CheckConstant(S, OpPC, Ptr.getDeclDesc());
+}
+
 bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   return !Ptr.isZero() && !Ptr.isDummy();
 }
@@ -303,6 +331,8 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   if (!CheckDummy(S, OpPC, Ptr))
 return false;
+  if (!CheckConstant(S, OpPC, Ptr))
+return false;
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
@@ -601,13 +631,7 @@ bool CheckDeclRef(InterpState &S, CodePtr OpPC, const 
DeclRefExpr *DR) {
 }
   } else if (const auto *VD = dyn_cast(D)) {
 if (!VD->getType().isConstQualified()) {
-  S.FFDiag(E,
-   VD->getType()->isIntegralOrEnumerationType()
-   ? diag::note_constexpr_ltor_non_const_int
-   : diag::note_constexpr_ltor_non_constexpr,
-   1)
-  << VD;
-  S.Note(VD->getLocation(), diag::note_declared_at) << 
VD->getSourceRange();
+  diagnoseNonConstVariable(S, OpPC, VD);
   return false;
 }
 
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 7dd415d6e460536..5b7bd9916c02b57 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -78,6 +78,9 @@ bool CheckSubobject(InterpState &S, CodePtr OpPC, const 
Po

[clang] [clang][Interp] Diagnose reads from non-const global variables (PR #71919)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

This fixes a long-standing FIXME item.

Unfortunately it changes the diagnostic output of the tests added in 
`cxx23.cpp`, but they were wrong before and are wrong after, so no big deal.

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


7 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+1-1) 
- (modified) clang/lib/AST/Interp/Interp.cpp (+34-10) 
- (modified) clang/lib/AST/Interp/Interp.h (+14) 
- (modified) clang/lib/AST/Interp/Opcodes.td (+1) 
- (modified) clang/test/AST/Interp/arrays.cpp (+32) 
- (modified) clang/test/AST/Interp/cxx23.cpp (+16-9) 
- (modified) clang/test/AST/Interp/literals.cpp (+24-3) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 15a717089660337..eca31efc85272bf 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2125,7 +2125,7 @@ bool ByteCodeExprGen::visitDecl(const VarDecl 
*VD) {
 auto GlobalIndex = P.getGlobal(VD);
 assert(GlobalIndex); // visitVarDecl() didn't return false.
 if (VarT) {
-  if (!this->emitGetGlobal(*VarT, *GlobalIndex, VD))
+  if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
 return false;
 } else {
   if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 144b674451e353c..d1d812a591591bf 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -53,6 +53,18 @@ static bool Jf(InterpState &S, CodePtr &PC, int32_t Offset) {
   return true;
 }
 
+static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
+ const ValueDecl *VD) {
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
+  S.FFDiag(Loc,
+   VD->getType()->isIntegralOrEnumerationType()
+   ? diag::note_constexpr_ltor_non_const_int
+   : diag::note_constexpr_ltor_non_constexpr,
+   1)
+  << VD;
+  S.Note(VD->getLocation(), diag::note_declared_at);
+}
+
 static bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
 AccessKinds AK) {
   if (Ptr.isActive())
@@ -170,9 +182,7 @@ bool CheckExtern(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
 
   if (!S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus) {
 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
-S.Note(VD->getLocation(), diag::note_declared_at);
+diagnoseNonConstVariable(S, OpPC, VD);
   }
   return false;
 }
@@ -215,6 +225,24 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr,
   return true;
 }
 
+bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc) {
+  assert(Desc);
+  if (const auto *D = Desc->asValueDecl()) {
+if (const auto *VD = dyn_cast(D);
+VD && VD->hasGlobalStorage() &&
+!(VD->isConstexpr() || VD->getType().isConstQualified())) {
+  diagnoseNonConstVariable(S, OpPC, VD);
+  return false;
+}
+  }
+
+  return true;
+}
+
+static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  return CheckConstant(S, OpPC, Ptr.getDeclDesc());
+}
+
 bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   return !Ptr.isZero() && !Ptr.isDummy();
 }
@@ -303,6 +331,8 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   if (!CheckDummy(S, OpPC, Ptr))
 return false;
+  if (!CheckConstant(S, OpPC, Ptr))
+return false;
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
@@ -601,13 +631,7 @@ bool CheckDeclRef(InterpState &S, CodePtr OpPC, const 
DeclRefExpr *DR) {
 }
   } else if (const auto *VD = dyn_cast(D)) {
 if (!VD->getType().isConstQualified()) {
-  S.FFDiag(E,
-   VD->getType()->isIntegralOrEnumerationType()
-   ? diag::note_constexpr_ltor_non_const_int
-   : diag::note_constexpr_ltor_non_constexpr,
-   1)
-  << VD;
-  S.Note(VD->getLocation(), diag::note_declared_at) << 
VD->getSourceRange();
+  diagnoseNonConstVariable(S, OpPC, VD);
   return false;
 }
 
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 7dd415d6e460536..5b7bd9916c02b57 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -78,6 +78,9 @@ bool CheckSubobject(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 /// Checks if a pointer points to const storage.
 bool CheckConst(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
 
+/// Checks if the Descriptor is of a constexpr or const global variable.
+bool 

[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Björn Pettersson via cfe-commits


@@ -0,0 +1,11 @@
+// RUN: cp %s %t.c

bjope wrote:

Well, I forgot to add the [[]] thing around the call. Now I'm back on track 
again :-)

https://github.com/llvm/llvm-project/pull/71162
___
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-10 Thread Liviu Ionescu via cfe-commits

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

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

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

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

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

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

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

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

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

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

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

[llvm] [flang] [clang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Tom Eccles via cfe-commits

https://github.com/tblah updated https://github.com/llvm/llvm-project/pull/71734

>From ac9c18ef7d286147fd1ae4a49efe343644d2ccd1 Mon Sep 17 00:00:00 2001
From: Tom Eccles 
Date: Tue, 7 Nov 2023 18:55:20 +
Subject: [PATCH 1/2] [flang] add fveclib flag

-fveclib= allows users to choose a vectorized libm so that loops
containing math functions can be vectorized.

This is implemented as much as possible in the same way as in clang.
The driver test in veclib.f90 is copied from the clang test.
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 34 +++
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/include/flang/Frontend/CodeGenOptions.h | 11 
 flang/lib/Frontend/CompilerInvocation.cpp | 29 ++
 flang/lib/Frontend/FrontendActions.cpp| 58 ---
 flang/test/Driver/driver-help-hidden.f90  |  1 +
 flang/test/Driver/driver-help.f90 |  2 +
 flang/test/Driver/fveclib-codegen.f90 | 13 +
 flang/test/Driver/fveclib.f90 | 30 ++
 10 files changed, 172 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Driver/fveclib-codegen.f90
 create mode 100644 flang/test/Driver/fveclib.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 36052511203f65c..f275ec68e710769 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3118,7 +3118,7 @@ def fno_global_isel : Flag<["-"], "fno-global-isel">, 
Group,
 def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, 
Group,
   Alias;
 def fveclib : Joined<["-"], "fveclib=">, Group,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
 HelpText<"Use the given vector functions library">,
 
Values<"Accelerate,libmvec,MASSV,SVML,SLEEF,Darwin_libsystem_m,ArmPL,none">,
 NormalizedValuesScope<"CodeGenOptions">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 999039f83ddfb92..b5ebbc4ef37e1db 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -232,6 +232,40 @@ void Flang::addTargetOptions(const ArgList &Args,
 break;
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
+StringRef Name = A->getValue();
+if (Name == "SVML") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "LIBMVEC-X86") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "SLEEF" || Name == "ArmPL") {
+  if (Triple.getArch() != llvm::Triple::aarch64 &&
+  Triple.getArch() != llvm::Triple::aarch64_be)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+}
+
+if (Triple.isOSDarwin()) {
+  // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
+  // here incase they are added someday
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+if (A->getValue() == StringRef{"Accelerate"}) {
+  CmdArgs.push_back("-framework");
+  CmdArgs.push_back("Accelerate");
+  A->render(Args, CmdArgs);
+}
+  }
+} else {
+  A->render(Args, CmdArgs);
+}
+  }
+
   // TODO: Add target specific flags, ABI, mtune option etc.
 }
 
diff --git a/flang/include/flang/Frontend/CodeGenOptions.def 
b/flang/include/flang/Frontend/CodeGenOptions.def
index 1e350869f1377e3..9d09ac1cbb251b1 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -37,6 +37,7 @@ CODEGENOPT(AliasAnalysis, 1, 0) ///< Enable alias analysis 
pass
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, llvm::Reloc::PIC_) 
///< Name of the relocation model to use.
 ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  
llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
+ENUM_CODEGENOPT(VecLib, VectorLibrary, 3, VectorLibrary::NoLibrary) ///< 
Vector functions library to use
 
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b0e0c91e09ab38f..1eb2264560a02fa 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -81,6 +81,17 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  enum class VectorLibrary {
+NoLibrary,  // Don't use any

[PATCH] D138846: MC/DC in LLVM Source-Based Code Coverage: LLVM back-end and compiler-rt

2023-11-10 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.

Code built with older versions of LLVM (e.g. rust) and running with the updated 
runtime crash at startup with this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138846

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


[llvm] [clang] [clang-tools-extra] [RFC] Perform lifetime bound checks for arguments to coroutine (PR #69360)

2023-11-10 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/69360

>From be3f5faa6cd17d76f26fb1bc6d6b59a8a78ffe82 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Tue, 17 Oct 2023 19:37:28 +0200
Subject: [PATCH 1/2] Lifetime bound check for coroutine

---
 clang/lib/Sema/SemaInit.cpp   |  16 +-
 .../SemaCXX/coroutine-lifetimebound-args.cpp  | 184 ++
 2 files changed, 198 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/coroutine-lifetimebound-args.cpp

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index fd95b16b84b6e3a..54e72b220bc47a4 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -7607,11 +7607,23 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 
   if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
 VisitLifetimeBoundArg(Callee, ObjectArg);
-
+  bool checkCoroCall = false;
+  if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
+for (const auto &attr :
+ RD->getUnderlyingDecl()->specific_attrs()) {
+  // Only for demonstration: Get feedback and add a clang annotation as an
+  // extension.
+  if (attr->getAnnotation() == "coro_type") {
+
+checkCoroCall = true;
+break;
+  }
+}
+  }
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
-if (Callee->getParamDecl(I)->hasAttr())
+if (checkCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
   }
 }
diff --git a/clang/test/SemaCXX/coroutine-lifetimebound-args.cpp 
b/clang/test/SemaCXX/coroutine-lifetimebound-args.cpp
new file mode 100644
index 000..4cc5730ef896581
--- /dev/null
+++ b/clang/test/SemaCXX/coroutine-lifetimebound-args.cpp
@@ -0,0 +1,184 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 -fsyntax-only 
-verify -Wall -Wextra -Wno-error=unreachable-code -Wno-unused
+
+#include "Inputs/std-coroutine.h"
+
+using std::suspend_always;
+using std::suspend_never;
+
+
+#define CORO_TYPE [[clang::annotate("coro_type")]]
+#define CORO_UNSAFE [[clang::annotate("coro_unsafe")]]
+
+template  struct CORO_TYPE Gen {
+  struct promise_type {
+Gen get_return_object() {
+  return {};
+}
+suspend_always initial_suspend();
+suspend_always final_suspend() noexcept;
+void unhandled_exception();
+void return_value(const T &t);
+
+template 
+auto await_transform(const Gen &) {
+  struct awaitable {
+bool await_ready() noexcept { return false; }
+void await_suspend(std::coroutine_handle<>) noexcept {}
+U await_resume() noexcept { return {}; }
+  };
+  return awaitable{};
+}
+  };
+};
+
+template  using Co = Gen;
+
+Gen foo_coro(const int& b);
+
+Gen plain_return_foo_decl(int b) {
+  return foo_coro(b); // expected-warning {{address of stack memory associated 
with parameter}}
+}
+
+Gen foo_coro(const int& b) {
+  if (b > 0)
+co_return 1;
+  co_return 2;
+}
+
+int getInt() { return 0; }
+
+Co bar_coro(const int &b, int c) {
+  int x = co_await foo_coro(b);
+  int y = co_await foo_coro(1);
+  int z = co_await foo_coro(getInt());
+  auto unsafe1 = foo_coro(1); // expected-warning {{temporary whose address is 
used as value of local variable}}
+  auto unsafe2 = foo_coro(getInt()); // expected-warning {{temporary whose 
address is used as value of local variable}}
+  auto  safe1 = foo_coro(b);
+  auto  safe2 = foo_coro(c);
+  co_return co_await foo_coro(co_await foo_coro(1));
+}
+
+Gen plain_return_co(int b) {
+  return foo_coro(b); // expected-warning {{address of stack memory associated 
with parameter}}
+}
+
+Gen safe_forwarding(const int& b) {
+  return foo_coro(b);
+}
+
+Gen unsafe_wrapper(int b) {
+  return safe_forwarding(b); // expected-warning {{address of stack memory 
associated with parameter}}
+}
+
+Co complex_plain_return(int b) {
+  return b > 0 
+  ? foo_coro(1)   // expected-warning {{returning address of local 
temporary object}}
+  : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
+}
+
+void lambdas() {
+  auto unsafe_lambda = [](int b) {
+return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
+  };
+  auto safe_lambda = [](int b) -> Co {
+int x = co_await foo_coro(1);
+co_return x + co_await foo_coro(b);
+  };
+}
+// 
=
+// Safe usage when parameters are value
+// 
=
+namespace by_value {
+Gen value_coro(int b) { co_return co_await foo_coro(b); }
+
+Gen wrapper1(int b) { return value_coro(b); }
+Gen wrapper2(const int& b) { return value_coro(b); }
+}
+
+// 
=
+// std::

[llvm] [clang] [clang-tools-extra] [RFC] Perform lifetime bound checks for arguments to coroutine (PR #69360)

2023-11-10 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/69360

>From be3f5faa6cd17d76f26fb1bc6d6b59a8a78ffe82 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Tue, 17 Oct 2023 19:37:28 +0200
Subject: [PATCH 1/3] Lifetime bound check for coroutine

---
 clang/lib/Sema/SemaInit.cpp   |  16 +-
 .../SemaCXX/coroutine-lifetimebound-args.cpp  | 184 ++
 2 files changed, 198 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/coroutine-lifetimebound-args.cpp

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index fd95b16b84b6e3a..54e72b220bc47a4 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -7607,11 +7607,23 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 
   if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
 VisitLifetimeBoundArg(Callee, ObjectArg);
-
+  bool checkCoroCall = false;
+  if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
+for (const auto &attr :
+ RD->getUnderlyingDecl()->specific_attrs()) {
+  // Only for demonstration: Get feedback and add a clang annotation as an
+  // extension.
+  if (attr->getAnnotation() == "coro_type") {
+
+checkCoroCall = true;
+break;
+  }
+}
+  }
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
-if (Callee->getParamDecl(I)->hasAttr())
+if (checkCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
   }
 }
diff --git a/clang/test/SemaCXX/coroutine-lifetimebound-args.cpp 
b/clang/test/SemaCXX/coroutine-lifetimebound-args.cpp
new file mode 100644
index 000..4cc5730ef896581
--- /dev/null
+++ b/clang/test/SemaCXX/coroutine-lifetimebound-args.cpp
@@ -0,0 +1,184 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 -fsyntax-only 
-verify -Wall -Wextra -Wno-error=unreachable-code -Wno-unused
+
+#include "Inputs/std-coroutine.h"
+
+using std::suspend_always;
+using std::suspend_never;
+
+
+#define CORO_TYPE [[clang::annotate("coro_type")]]
+#define CORO_UNSAFE [[clang::annotate("coro_unsafe")]]
+
+template  struct CORO_TYPE Gen {
+  struct promise_type {
+Gen get_return_object() {
+  return {};
+}
+suspend_always initial_suspend();
+suspend_always final_suspend() noexcept;
+void unhandled_exception();
+void return_value(const T &t);
+
+template 
+auto await_transform(const Gen &) {
+  struct awaitable {
+bool await_ready() noexcept { return false; }
+void await_suspend(std::coroutine_handle<>) noexcept {}
+U await_resume() noexcept { return {}; }
+  };
+  return awaitable{};
+}
+  };
+};
+
+template  using Co = Gen;
+
+Gen foo_coro(const int& b);
+
+Gen plain_return_foo_decl(int b) {
+  return foo_coro(b); // expected-warning {{address of stack memory associated 
with parameter}}
+}
+
+Gen foo_coro(const int& b) {
+  if (b > 0)
+co_return 1;
+  co_return 2;
+}
+
+int getInt() { return 0; }
+
+Co bar_coro(const int &b, int c) {
+  int x = co_await foo_coro(b);
+  int y = co_await foo_coro(1);
+  int z = co_await foo_coro(getInt());
+  auto unsafe1 = foo_coro(1); // expected-warning {{temporary whose address is 
used as value of local variable}}
+  auto unsafe2 = foo_coro(getInt()); // expected-warning {{temporary whose 
address is used as value of local variable}}
+  auto  safe1 = foo_coro(b);
+  auto  safe2 = foo_coro(c);
+  co_return co_await foo_coro(co_await foo_coro(1));
+}
+
+Gen plain_return_co(int b) {
+  return foo_coro(b); // expected-warning {{address of stack memory associated 
with parameter}}
+}
+
+Gen safe_forwarding(const int& b) {
+  return foo_coro(b);
+}
+
+Gen unsafe_wrapper(int b) {
+  return safe_forwarding(b); // expected-warning {{address of stack memory 
associated with parameter}}
+}
+
+Co complex_plain_return(int b) {
+  return b > 0 
+  ? foo_coro(1)   // expected-warning {{returning address of local 
temporary object}}
+  : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
+}
+
+void lambdas() {
+  auto unsafe_lambda = [](int b) {
+return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
+  };
+  auto safe_lambda = [](int b) -> Co {
+int x = co_await foo_coro(1);
+co_return x + co_await foo_coro(b);
+  };
+}
+// 
=
+// Safe usage when parameters are value
+// 
=
+namespace by_value {
+Gen value_coro(int b) { co_return co_await foo_coro(b); }
+
+Gen wrapper1(int b) { return value_coro(b); }
+Gen wrapper2(const int& b) { return value_coro(b); }
+}
+
+// 
=
+// std::

[llvm] [clang] [clang-tools-extra] [AMDGPU] Fix GCNUpwardRPTracker. (WIP) (PR #71186)

2023-11-10 Thread Valery Pykhtin via cfe-commits

https://github.com/vpykhtin updated 
https://github.com/llvm/llvm-project/pull/71186

>From e2254cb744adb65685edeb2373f900368c11c11a Mon Sep 17 00:00:00 2001
From: Valery Pykhtin 
Date: Thu, 2 Nov 2023 20:39:11 +0100
Subject: [PATCH 1/3] [AMDGPU] Fix GCNUpwardRPTracker.

---
 .../Target/AMDGPU/GCNIterativeScheduler.cpp   |   4 +-
 llvm/lib/Target/AMDGPU/GCNRegPressure.cpp | 135 -
 llvm/lib/Target/AMDGPU/GCNRegPressure.h   |  47 --
 .../CodeGen/AMDGPU/regpressure_printer.mir| 137 +++---
 4 files changed, 190 insertions(+), 133 deletions(-)

diff --git a/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp 
b/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp
index d89c9b1febded0f..cdc9de7f65e3e50 100644
--- a/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNIterativeScheduler.cpp
@@ -251,7 +251,7 @@ 
GCNIterativeScheduler::getRegionPressure(MachineBasicBlock::iterator Begin,
   assert(UPTracker.isValid() ||
  (dbgs() << "Tracked region ",
   printRegion(dbgs(), Begin, End, LIS), false));
-  return UPTracker.moveMaxPressure();
+  return UPTracker.getMaxPressureAndReset();
 }
 
 // returns max pressure for a tentative schedule
@@ -272,7 +272,7 @@ GCNIterativeScheduler::getSchedulePressure(const Region &R,
   for (auto I = Schedule.end(), B = Schedule.begin(); I != B;) {
 RPTracker.recede(*getMachineInstr(*--I));
   }
-  return RPTracker.moveMaxPressure();
+  return RPTracker.getMaxPressureAndReset();
 }
 
 void GCNIterativeScheduler::enterRegion(MachineBasicBlock *BB, // overridden
diff --git a/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp 
b/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp
index a04c470b7b9762f..f191f3f08c56c6d 100644
--- a/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp
@@ -166,66 +166,62 @@ static LaneBitmask getDefRegMask(const MachineOperand &MO,
 MRI.getTargetRegisterInfo()->getSubRegIndexLaneMask(MO.getSubReg());
 }
 
-static LaneBitmask getUsedRegMask(const MachineOperand &MO,
-  const MachineRegisterInfo &MRI,
-  const LiveIntervals &LIS) {
-  assert(MO.isUse() && MO.isReg() && MO.getReg().isVirtual());
-
-  if (auto SubReg = MO.getSubReg())
-return MRI.getTargetRegisterInfo()->getSubRegIndexLaneMask(SubReg);
-
-  auto MaxMask = MRI.getMaxLaneMaskForVReg(MO.getReg());
-  if (SIRegisterInfo::getNumCoveredRegs(MaxMask) > 1) // cannot have subregs
-return MaxMask;
-
-  // For a tentative schedule LIS isn't updated yet but livemask should remain
-  // the same on any schedule. Subreg defs can be reordered but they all must
-  // dominate uses anyway.
-  auto SI = LIS.getInstructionIndex(*MO.getParent()).getBaseIndex();
-  return getLiveLaneMask(MO.getReg(), SI, LIS, MRI);
-}
-
-static SmallVector
-collectVirtualRegUses(const MachineInstr &MI, const LiveIntervals &LIS,
+static void
+collectVirtualRegUses(SmallVectorImpl &RegMaskPairs,
+  const MachineInstr &MI, const LiveIntervals &LIS,
   const MachineRegisterInfo &MRI) {
-  SmallVector Res;
+  SlotIndex InstrSI;
   for (const auto &MO : MI.operands()) {
 if (!MO.isReg() || !MO.getReg().isVirtual())
   continue;
 if (!MO.isUse() || !MO.readsReg())
   continue;
 
-auto const UsedMask = getUsedRegMask(MO, MRI, LIS);
+Register Reg = MO.getReg();
+auto I = llvm::find_if(RegMaskPairs, [Reg](const RegisterMaskPair &RM) {
+  return RM.RegUnit == Reg;
+});
+if (I != RegMaskPairs.end())
+  continue;
+  
+LaneBitmask UseMask;
+auto &LI = LIS.getInterval(Reg);
+if (!LI.hasSubRanges())
+  UseMask = MRI.getMaxLaneMaskForVReg(Reg);
+else {
+  // For a tentative schedule LIS isn't updated yet but livemask should
+  // remain the same on any schedule. Subreg defs can be reordered but they
+  // all must dominate uses anyway.
+  if (!InstrSI)
+InstrSI = LIS.getInstructionIndex(*MO.getParent()).getBaseIndex();
+  UseMask = getLiveLaneMask(LI, InstrSI, MRI);
+}
 
-auto Reg = MO.getReg();
-auto I = llvm::find_if(
-Res, [Reg](const RegisterMaskPair &RM) { return RM.RegUnit == Reg; });
-if (I != Res.end())
-  I->LaneMask |= UsedMask;
-else
-  Res.push_back(RegisterMaskPair(Reg, UsedMask));
+RegMaskPairs.emplace_back(Reg, UseMask);
   }
-  return Res;
 }
 
 ///
 // GCNRPTracker
 
-LaneBitmask llvm::getLiveLaneMask(unsigned Reg,
-  SlotIndex SI,
+LaneBitmask llvm::getLiveLaneMask(unsigned Reg, SlotIndex SI,
   const LiveIntervals &LIS,
   const MachineRegisterInfo &MRI) {
+  return getLiveLaneMask(LIS.getInterval(Reg), SI, MRI);
+}
+
+LaneBitmask llvm::getLiveLaneMask(const LiveInterval &LI, SlotIndex SI,
+   

[clang] 9f265c3 - [flang][driver] add -flang-deprecated-no-hlfir hidden option (#71820)

2023-11-10 Thread via cfe-commits

Author: jeanPerier
Date: 2023-11-10T11:54:10+01:00
New Revision: 9f265c38718ca5c6b2b2ba6a237db1ba5e2cac55

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

LOG: [flang][driver] add -flang-deprecated-no-hlfir hidden option (#71820)

Patch 1/3 of the transition to use the HLFIR step by default in lowering
as described in
https://discourse.llvm.org/t/rfc-enabling-the-hlfir-lowering-by-default/72778/7

This option will allow to lower code without the HLFIR step during a
grace period as described in the RFC. It is not meant to be a long term
switch for flang.

Added: 
flang/test/Driver/hlfir-no-hlfir-error.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/lib/Frontend/CompilerInvocation.cpp
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/frontend-forwarding.f90
flang/test/HLFIR/hlfir-flags.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5d065cef778a7d8..3409ce29ac56302 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6218,6 +6218,10 @@ def flang_experimental_hlfir : Flag<["-"], 
"flang-experimental-hlfir">,
   Flags<[HelpHidden]>, Visibility<[FlangOption, FC1Option]>,
   HelpText<"Use HLFIR lowering (experimental)">;
 
+def flang_deprecated_no_hlfir : Flag<["-"], "flang-deprecated-no-hlfir">,
+  Flags<[HelpHidden]>, Visibility<[FlangOption, FC1Option]>,
+  HelpText<"Do not use HLFIR lowering (deprecated)">;
+
 def flang_experimental_polymorphism : Flag<["-"], 
"flang-experimental-polymorphism">,
   Flags<[HelpHidden]>, Visibility<[FlangOption, FC1Option]>,
   HelpText<"Enable Fortran 2003 polymorphism (experimental)">;

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 999039f83ddfb92..ce0f7e4da006d5f 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -143,6 +143,7 @@ void Flang::addCodegenOptions(const ArgList &Args,
 CmdArgs.push_back("-fversion-loops-for-stride");
 
   Args.addAllArgs(CmdArgs, {options::OPT_flang_experimental_hlfir,
+options::OPT_flang_deprecated_no_hlfir,
 options::OPT_flang_experimental_polymorphism,
 options::OPT_fno_ppc_native_vec_elem_order,
 options::OPT_fppc_native_vec_elem_order,

diff  --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index ba2ecab3742587a..3fef3771ed0da0d 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -1073,6 +1073,19 @@ bool CompilerInvocation::createFromArgs(
 res.loweringOpts.setLowerToHighLevelFIR(true);
   }
 
+  // -flang-deprecated-no-hlfir
+  if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) &&
+  !args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
+if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) {
+  const unsigned diagID = diags.getCustomDiagID(
+  clang::DiagnosticsEngine::Error,
+  "Options '-flang-experimental-hlfir' and "
+  "'-flang-deprecated-no-hlfir' cannot be both specified");
+  diags.Report(diagID);
+}
+res.loweringOpts.setLowerToHighLevelFIR(false);
+  }
+
   if 
(args.hasArg(clang::driver::options::OPT_flang_experimental_polymorphism)) {
 res.loweringOpts.setPolymorphicTypeImpl(true);
   }

diff  --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 6d399f1d179a022..5e0e459c21c93e2 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -49,6 +49,8 @@
 ! CHECK-NEXT: -fintegrated-as Enable the integrated assembler
 ! CHECK-NEXT: -fintrinsic-modules-path 
 ! CHECK-NEXT: Specify where to find the compiled 
intrinsic modules
+! CHECK-NEXT: -flang-deprecated-no-hlfir
+! CHECK-NEXT: Do not use HLFIR lowering (deprecated)
 ! CHECK-NEXT: -flang-experimental-hlfir
 ! CHECK-NEXT: Use HLFIR lowering (experimental)
 ! CHECK-NEXT: -flang-experimental-polymorphism

diff  --git a/flang/test/Driver/frontend-forwarding.f90 
b/flang/test/Driver/frontend-forwarding.f90
index 520f4898feb0a6b..20455791c9ff4d6 100644
--- a/flang/test/Driver/frontend-forwarding.f90
+++ b/flang/test/Driver/frontend-forwarding.f90
@@ -18,6 +18,7 @@
 ! RUN: -fversion-loops-for-stride \
 ! RUN: -flang-experimental-polymorphism \
 ! RUN: -flang-experimental-hlfir \
+! RUN: -flang-deprecated-no-hlfir \
 ! RUN: -fno-ppc-native-vector-element-order \
 ! RUN: -f

[clang] [flang] [flang][driver] add -flang-deprecated-no-hlfir hidden option (PR #71820)

2023-11-10 Thread via cfe-commits

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


[clang] [flang] [flang][driver] add -flang-deprecated-no-hlfir hidden option (PR #71820)

2023-11-10 Thread via cfe-commits

jeanPerier wrote:

> Yes I meant hlfir-flags.f90. Sorry about that. Thanks for the changes!
No problem, thanks for the review and comments!


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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Björn Pettersson via cfe-commits

https://github.com/bjope updated https://github.com/llvm/llvm-project/pull/71162

From 1fb659fa15568ec8256824339860de724853c6e3 Mon Sep 17 00:00:00 2001
From: Bjorn Pettersson 
Date: Thu, 2 Nov 2023 22:00:52 +0100
Subject: [PATCH 1/2] [clangd] Check for valid source location in
 ExtractionContext::exprIsValidOutside

If the code has a call to an implicitly declared function, an
expression could end up referencing declarations without valid
source locations. So when doing the exprIsValidOutside check we
could end up calling SourceManager::isPointWithin using invalid
source locations, and then a debug build would crash with an
assertion failure in SourceManager::isBeforeInTranslationUnit.

This patch make sure that we deal with the invalid locations
(by considering a ReferencedDecl with invalid location as not
being inside the Scope).
---
 .../clangd/refactor/tweaks/ExtractVariable.cpp|  3 ++-
 clang-tools-extra/clangd/test/implicit-function.test  | 11 +++
 2 files changed, 13 insertions(+), 1 deletion(-)
 create mode 100644 clang-tools-extra/clangd/test/implicit-function.test

diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
index 1e4edc6d6b4bb39..79bf962544242bb 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
@@ -176,7 +176,8 @@ bool ExtractionContext::exprIsValidOutside(const 
clang::Stmt *Scope) const {
   SourceLocation ScopeBegin = Scope->getBeginLoc();
   SourceLocation ScopeEnd = Scope->getEndLoc();
   for (const Decl *ReferencedDecl : ReferencedDecls) {
-if (SM.isPointWithin(ReferencedDecl->getBeginLoc(), ScopeBegin, ScopeEnd) 
&&
+if (ReferencedDecl->getBeginLoc().isValid() &&
+SM.isPointWithin(ReferencedDecl->getBeginLoc(), ScopeBegin, ScopeEnd) 
&&
 SM.isPointWithin(ReferencedDecl->getEndLoc(), ScopeBegin, ScopeEnd))
   return false;
   }
diff --git a/clang-tools-extra/clangd/test/implicit-function.test 
b/clang-tools-extra/clangd/test/implicit-function.test
new file mode 100644
index 000..85731f358b4ae8e
--- /dev/null
+++ b/clang-tools-extra/clangd/test/implicit-function.test
@@ -0,0 +1,11 @@
+// RUN: cp %s %t.c
+// RUN: not clangd -enable-config=0 -log=verbose -check=%t.c 2>&1 | FileCheck 
-strict-whitespace %s
+
+// Regression test for a situation when we used to hit an assertion failure
+// due to missing source location (for the implicit function declaration).
+
+// CHECK-DAG: [-Wimplicit-function-declaration] Line {{.*}}: call to 
undeclared function 'foo'
+// CHECK-DAG: [init_element_not_constant] Line {{.*}}: initializer element is 
not a compile-time constant
+// CHECK: All checks completed, 2 errors
+
+int x = foo();

From 58084d9b753c08be76fe0b171297352e84d61f87 Mon Sep 17 00:00:00 2001
From: Bjorn Pettersson 
Date: Fri, 10 Nov 2023 11:54:25 +0100
Subject: [PATCH 2/2] TO BE SQUASHED

Changed the regression test into using unittest.
---
 clang-tools-extra/clangd/test/implicit-function.test  | 11 ---
 .../clangd/unittests/tweaks/ExtractVariableTests.cpp  |  8 
 2 files changed, 8 insertions(+), 11 deletions(-)
 delete mode 100644 clang-tools-extra/clangd/test/implicit-function.test

diff --git a/clang-tools-extra/clangd/test/implicit-function.test 
b/clang-tools-extra/clangd/test/implicit-function.test
deleted file mode 100644
index 85731f358b4ae8e..000
--- a/clang-tools-extra/clangd/test/implicit-function.test
+++ /dev/null
@@ -1,11 +0,0 @@
-// RUN: cp %s %t.c
-// RUN: not clangd -enable-config=0 -log=verbose -check=%t.c 2>&1 | FileCheck 
-strict-whitespace %s
-
-// Regression test for a situation when we used to hit an assertion failure
-// due to missing source location (for the implicit function declaration).
-
-// CHECK-DAG: [-Wimplicit-function-declaration] Line {{.*}}: call to 
undeclared function 'foo'
-// CHECK-DAG: [init_element_not_constant] Line {{.*}}: initializer element is 
not a compile-time constant
-// CHECK: All checks completed, 2 errors
-
-int x = foo();
diff --git a/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
index 3d74a941071f849..eb5b06cfee43166 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
@@ -64,6 +64,14 @@ TEST_F(ExtractVariableTest, Test) {
   int x = [[1]];
 })cpp";
   EXPECT_AVAILABLE(AvailableC);
+
+  ExtraArgs = {"-xc"};
+  const char *NoCrashCasesC = R"cpp(
+// error-ok: broken code, but shouldn't crash
+int x = [[foo()]];
+)cpp";
+  EXPECT_UNAVAILABLE(NoCrashCasesC);
+
   ExtraArgs = {"-xobjective-c"};
   const char *AvailableObjC = R"cpp(
 __attribute__((objc_root_class))

___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[llvm] [clang] [clang-tools-extra] [AMDGPU] Fix GCNUpwardRPTracker. (WIP) (PR #71186)

2023-11-10 Thread Valery Pykhtin via cfe-commits


@@ -128,14 +128,7 @@ class GCNRPTracker {
 
   void clearMaxPressure() { MaxPressure.clear(); }
 
-  GCNRegPressure getPressure() const { return CurPressure; }
-
-  // returns MaxPressure, resetting it
-  decltype(MaxPressure) moveMaxPressure() {
-auto Res = MaxPressure;
-MaxPressure.clear();
-return Res;
-  }
+  const GCNRegPressure &getPressure() const { return CurPressure; }

vpykhtin wrote:

Done.

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


[llvm] [clang] [clang-tools-extra] [AMDGPU] Fix GCNUpwardRPTracker. (WIP) (PR #71186)

2023-11-10 Thread Valery Pykhtin via cfe-commits


@@ -180,6 +190,13 @@ class GCNDownwardRPTracker : public GCNRPTracker {
 
   MachineBasicBlock::const_iterator getNext() const { return NextMI; }
 
+  // Return MaxPressure and clear it.
+  decltype(MaxPressure) moveMaxPressure() {

vpykhtin wrote:

Done.

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


[clang] [Clang][SME2] Add single and multi min/max by vector builtins (PR #71707)

2023-11-10 Thread Dinar Temirbulatov via cfe-commits

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

LGTM

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


[clang] [clang-format] Remove special handling of comments after brace/paren (PR #71672)

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

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


[clang] [clang-format] Remove special handling of comments after brace/paren (PR #71672)

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

https://github.com/HazardyKnusperkeks updated 
https://github.com/llvm/llvm-project/pull/71672

From aeec6f1e767bc2bb11823cb694bf6ccc267b060d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= 
Date: Wed, 8 Nov 2023 13:31:32 +0100
Subject: [PATCH] [clang-format] Remove special handling of comments after
 brace/paren

Fixes http://llvm.org/PR55487 (#55487)

The code did not match the documentation about Cpp11BracedListStyle.
Changed handling of comments after opening braces, which are supposedly
function call like to behave exactly like their parenthesis counter
part.
---
 clang/lib/Format/ContinuationIndenter.cpp |  5 +-
 clang/lib/Format/TokenAnnotator.cpp   | 13 +---
 clang/unittests/Format/FormatTest.cpp | 18 +++---
 clang/unittests/Format/FormatTestComments.cpp | 61 +--
 4 files changed, 70 insertions(+), 27 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 3a829cdedb77fc7..04b799a0ea275e1 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -802,7 +802,10 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
   !(Current.MacroParent && Previous.MacroParent) &&
   (Current.isNot(TT_LineComment) ||
-   Previous.isOneOf(BK_BracedInit, TT_VerilogMultiLineListLParen))) {
+   (Previous.is(BK_BracedInit) &&
+(!Style.Cpp11BracedListStyle || !Previous.Previous ||
+ Previous.Previous->isNot(tok::identifier))) ||
+   Previous.is(TT_VerilogMultiLineListLParen))) {
 CurrentState.Indent = State.Column + Spaces;
 CurrentState.IsAligned = true;
   }
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index d648e441f23fe9e..25c9666b0b726ca 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3507,16 +3507,9 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
   while (Current) {
 const FormatToken *Prev = Current->Previous;
 if (Current->is(TT_LineComment)) {
-  if (Prev->is(BK_BracedInit) && Prev->opensScope()) {
-Current->SpacesRequiredBefore =
-(Style.Cpp11BracedListStyle && !Style.SpacesInParensOptions.Other)
-? 0
-: 1;
-  } else if (Prev->is(TT_VerilogMultiLineListLParen)) {
-Current->SpacesRequiredBefore = 0;
-  } else {
-Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
-  }
+  Current->SpacesRequiredBefore = Prev->is(TT_VerilogMultiLineListLParen)
+  ? 0
+  : Style.SpacesBeforeTrailingComments;
 
   // If we find a trailing comment, iterate backwards to determine whether
   // it seems to relate to a specific parameter. If so, break before that
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 80903e7630c8073..81a98c3158a425e 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -13500,20 +13500,18 @@ TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
"CDDDP83848_RBR_REGISTER};",
NoBinPacking);
 
-  // FIXME: The alignment of these trailing comments might be bad. Then again,
-  // this might be utterly useless in real code.
   verifyFormat("Constructor::Constructor()\n"
-   ": some_value{ //\n"
-   " aaa, //\n"
-   " bbb} {}");
+   ": some_value{  //\n"
+   "  aaa, //\n"
+   "  bbb} {}");
 
   // In braced lists, the first comment is always assumed to belong to the
   // first element. Thus, it can be moved to the next or previous line as
   // appropriate.
-  verifyFormat("function({// First element:\n"
-   "  1,\n"
-   "  // Second element:\n"
-   "  2});",
+  verifyFormat("function({ // First element:\n"
+   "   1,\n"
+   "   // Second element:\n"
+   "   2});",
"function({\n"
"// First element:\n"
"1,\n"
@@ -13635,7 +13633,7 @@ TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
   verifyFormat("vector< int > x{ // comment 1\n"
-   " 1, 2, 3, 4 };",
+   "1, 2, 3, 4 };",
SpaceBetweenBraces);
   SpaceBetweenBraces.ColumnLimit = 20;
   verifyFormat("vector< int > x{\n"
diff --git a/clang/unitte

[clang] [clang-format] Remove special handling of comments after brace/paren (PR #71672)

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

HazardyKnusperkeks wrote:

Updated implementation and tests for `Cpp1BracedListSyle` set to `false`.

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


[clang] [llvm] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Kiran Chandramohan via cfe-commits

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

Nice work. LGTM.

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


[llvm] [flang] [clang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Kiran Chandramohan via cfe-commits

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


[clang] [llvm] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Kiran Chandramohan via cfe-commits


@@ -111,7 +111,7 @@ int main(int argc, const char **argv) {
 
   auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), 
OFS);
 
-  auto Driver = std::make_unique(
+  auto Driver = std::make_unique(

kiranchandramohan wrote:

Are these clang prefixes required?

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


[llvm] [clang] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Kiran Chandramohan via cfe-commits


@@ -851,11 +851,10 @@ getOutputStream(CompilerInstance &ci, llvm::StringRef 
inFile,
 /// \param [in] act Backend act to run (assembly vs machine-code generation)
 /// \param [in] llvmModule LLVM module to lower to assembly/machine-code
 /// \param [out] os Output stream to emit the generated code to

kiranchandramohan wrote:

Nit: Add the new option here. May be good to have the stream as the last option.

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


[llvm] [clang] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Kiran Chandramohan via cfe-commits


@@ -0,0 +1,13 @@
+! test that -fveclib= is passed to the backend
+! -target aarch64 so that ArmPL is available
+! RUN: %flang -S -target aarch64-unknown-linux-gnu -mcpu=neoverse-v1 -Ofast 
-fveclib=ArmPL -o - %s | FileCheck %s
+

kiranchandramohan wrote:

Will this work on all targets? Or only on AArch64?

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


[llvm] [clang] [WIP][AMDGPU] Enable hostcall printf for OpenCL (PR #70932)

2023-11-10 Thread Vikram Hegde via cfe-commits

vikramRH wrote:

@b-sumner, @ssahasra , what are your thoughts about making the hostcall default 
throughout ?
Also I do not think splitting this into separate patches is feasible since 
changes are interdependent, however I could split changes into separate commits 
to make it easier to review.

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


[llvm] [clang] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Tom Eccles via cfe-commits


@@ -111,7 +111,7 @@ int main(int argc, const char **argv) {
 
   auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), 
OFS);
 
-  auto Driver = std::make_unique(
+  auto Driver = std::make_unique(

tblah wrote:

The file imports both the `clang` and `llvm` namespaces. So now that I have 
added `llvm::driver`, `driver::Driver` is ambiguous.

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


[llvm] [clang] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Tom Eccles via cfe-commits


@@ -0,0 +1,13 @@
+! test that -fveclib= is passed to the backend
+! -target aarch64 so that ArmPL is available
+! RUN: %flang -S -target aarch64-unknown-linux-gnu -mcpu=neoverse-v1 -Ofast 
-fveclib=ArmPL -o - %s | FileCheck %s
+

tblah wrote:

-fveclib should work on all targets which clang supports (I have only tested 
aarch64). ArmPL is only available on aarch64 (and this is enforced in the 
compiler driver) so I added the target here. I used ArmPL for the test because 
I know what the right result looks like for ArmPL, but not for other libraries.

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


[llvm] [clang] [AArch64][SME2] Add ldr_zt, str_zt builtins and intrinsics (PR #71795)

2023-11-10 Thread Sam Tebbs via cfe-commits




SamTebbs33 wrote:

Considering the definitions are commented out, are these changes necessary?

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


[clang] [AArch64][SME2] Enable bfm builtings for sme2 (PR #71927)

2023-11-10 Thread Sam Tebbs via cfe-commits

https://github.com/SamTebbs33 created 
https://github.com/llvm/llvm-project/pull/71927

This patch enables the following builtins for SME2
svbfmlslb_f32
svbfmlslb_lane_f32
svbfmlslt_f32
svbfmlslt_lane_f32

Patch by: Kerry McLaughlin 

>From ff33739706ce758f416153aa3cdb7c632e068da3 Mon Sep 17 00:00:00 2001
From: Samuel Tebbs 
Date: Thu, 9 Nov 2023 17:39:26 +
Subject: [PATCH] [AArch64][SME2] Enable bfm builtings for sme2

This patch enables the following builtins for SME2
svbfmlslb_f32
svbfmlslb_lane_f32
svbfmlslt_f32
svbfmlslt_lane_f32

Patch by: Kerry McLaughlin 
---
 clang/include/clang/Basic/arm_sve.td  | 15 +--
 .../acle_sve2p1_bfmlsl.c  |  5 +
 2 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 3d4c2129565903d..1094c424e68abd5 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1959,12 +1959,6 @@ def SVDOT_X2_F : SInst<"svdot[_{d}_{2}_{3}]", "ddhh", 
"f",  MergeNone, "aarch64_
 def SVDOT_LANE_X2_S : SInst<"svdot_lane[_{d}_{2}_{3}]", "ddhhi", "i",  
MergeNone, "aarch64_sve_sdot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
 def SVDOT_LANE_X2_U : SInst<"svdot_lane[_{d}_{2}_{3}]", "ddhhi", "Ui", 
MergeNone, "aarch64_sve_udot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
 def SVDOT_LANE_X2_F : SInst<"svdot_lane[_{d}_{2}_{3}]", "ddhhi", "f",  
MergeNone, "aarch64_sve_fdot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
-
-def SVBFMLSLB : SInst<"svbfmlslb[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslb", [IsOverloadNone], []>;
-def SVBFMLSLT : SInst<"svbfmlslt[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslt", [IsOverloadNone], []>;
-
-def SVBFMLSLB_LANE : SInst<"svbfmlslb_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslb_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
-def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslt_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
 }
 
 let TargetGuard = "sve2p1" in {
@@ -1992,3 +1986,12 @@ let TargetGuard = "sme2" in {
   def SVADD_SINGLE_X2 : SInst<"svadd[_single_{d}_x2]", "22d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x2", [IsStreaming], []>;
   def SVADD_SINGLE_X4 : SInst<"svadd[_single_{d}_x4]", "44d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x4", [IsStreaming], []>;
 }
+
+let TargetGuard = "sve2p1|sme" in {
+// == BFloat16 multiply-subtract ==
+  def SVBFMLSLB : SInst<"svbfmlslb[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslb", [IsOverloadNone], []>;
+  def SVBFMLSLT : SInst<"svbfmlslt[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslt", [IsOverloadNone], []>;
+
+  def SVBFMLSLB_LANE : SInst<"svbfmlslb_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslb_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
+  def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslt_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
+}
diff --git a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c 
b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
index 7e1763a63ec4e1d..519bf019ff35ba5 100644
--- a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
+++ b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
@@ -2,10 +2,15 @@
 // REQUIRES: aarch64-registered-target
 
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - %s 
| opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +sve -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - -x 
c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s 
-check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +sve -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
 // RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sve2p1 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s
+// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sme2 -target-feature +sve -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s
 // RUN: %clang_cc1 -fclang-

[clang] [AArch64][SME2] Enable bfm builtings for sme2 (PR #71927)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Sam Tebbs (SamTebbs33)


Changes

This patch enables the following builtins for SME2
svbfmlslb_f32
svbfmlslb_lane_f32
svbfmlslt_f32
svbfmlslt_lane_f32

Patch by: Kerry McLaughlin 

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


2 Files Affected:

- (modified) clang/include/clang/Basic/arm_sve.td (+9-6) 
- (modified) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c 
(+5) 


``diff
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 3d4c2129565903d..1094c424e68abd5 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1959,12 +1959,6 @@ def SVDOT_X2_F : SInst<"svdot[_{d}_{2}_{3}]", "ddhh", 
"f",  MergeNone, "aarch64_
 def SVDOT_LANE_X2_S : SInst<"svdot_lane[_{d}_{2}_{3}]", "ddhhi", "i",  
MergeNone, "aarch64_sve_sdot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
 def SVDOT_LANE_X2_U : SInst<"svdot_lane[_{d}_{2}_{3}]", "ddhhi", "Ui", 
MergeNone, "aarch64_sve_udot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
 def SVDOT_LANE_X2_F : SInst<"svdot_lane[_{d}_{2}_{3}]", "ddhhi", "f",  
MergeNone, "aarch64_sve_fdot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
-
-def SVBFMLSLB : SInst<"svbfmlslb[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslb", [IsOverloadNone], []>;
-def SVBFMLSLT : SInst<"svbfmlslt[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslt", [IsOverloadNone], []>;
-
-def SVBFMLSLB_LANE : SInst<"svbfmlslb_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslb_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
-def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslt_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
 }
 
 let TargetGuard = "sve2p1" in {
@@ -1992,3 +1986,12 @@ let TargetGuard = "sme2" in {
   def SVADD_SINGLE_X2 : SInst<"svadd[_single_{d}_x2]", "22d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x2", [IsStreaming], []>;
   def SVADD_SINGLE_X4 : SInst<"svadd[_single_{d}_x4]", "44d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x4", [IsStreaming], []>;
 }
+
+let TargetGuard = "sve2p1|sme" in {
+// == BFloat16 multiply-subtract ==
+  def SVBFMLSLB : SInst<"svbfmlslb[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslb", [IsOverloadNone], []>;
+  def SVBFMLSLT : SInst<"svbfmlslt[_{d}]", "dd$$", "f", MergeNone, 
"aarch64_sve_bfmlslt", [IsOverloadNone], []>;
+
+  def SVBFMLSLB_LANE : SInst<"svbfmlslb_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslb_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
+  def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", "dd$$i", "f", MergeNone, 
"aarch64_sve_bfmlslt_lane", [IsOverloadNone], [ImmCheck<3, ImmCheck0_7>]>;
+}
diff --git a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c 
b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
index 7e1763a63ec4e1d..519bf019ff35ba5 100644
--- a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
+++ b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
@@ -2,10 +2,15 @@
 // REQUIRES: aarch64-registered-target
 
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - %s 
| opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +sve -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - -x 
c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s 
-check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +sve -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
 // RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sve2p1 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s
+// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sme2 -target-feature +sve -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s
 // RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sve2p1 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -f

[llvm] [flang] [clang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Kiran Chandramohan via cfe-commits


@@ -0,0 +1,13 @@
+! test that -fveclib= is passed to the backend
+! -target aarch64 so that ArmPL is available
+! RUN: %flang -S -target aarch64-unknown-linux-gnu -mcpu=neoverse-v1 -Ofast 
-fveclib=ArmPL -o - %s | FileCheck %s
+

kiranchandramohan wrote:

I was asking whether this test needs to be restricted to only work on a system 
where Arm target is enabled.

https://github.com/llvm/llvm-project/pull/71734
___
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-10 Thread Michael Kruse via cfe-commits

Meinersbur wrote:

@owenca  You can run `ninja polly-update-format` which will use the in-tree 
`clang-format` to reformat all files. `git add` its changes, `git add --amend`, 
then push.

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] [clang][Interp] Handle SizeOfPackExprs (PR #71929)

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

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/71929

None

>From 1fe6815c82c1df26f35edcd64e85d4a2fd584f44 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 10 Nov 2023 13:04:30 +0100
Subject: [PATCH] [clang][Interp] Handle SizeOfPackExprs

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 5 +
 clang/lib/AST/Interp/ByteCodeExprGen.h   | 1 +
 clang/test/AST/Interp/functions.cpp  | 7 +++
 3 files changed, 13 insertions(+)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 15a717089660337..c8d3c1243fc1094 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1624,6 +1624,11 @@ bool 
ByteCodeExprGen::VisitCXXScalarValueInitExpr(
   return this->visitZeroInitializer(classifyPrim(Ty), Ty, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
+  return this->emitConst(E->getPackLength(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 83986d3dd579ed6..ec9b6bb1408453c 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -107,6 +107,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
+  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
diff --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 4bef9c2f7c0d1fa..ab562e70606b672 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -371,3 +371,10 @@ namespace Variadic {
   constexpr int (*VFP)(...) = variadic_function2;
   static_assert(VFP() == 12, "");
 }
+
+namespace Packs {
+  template
+  constexpr int foo() { return sizeof...(T); }
+  static_assert(foo() == 2, "");
+  static_assert(foo<>() == 0, "");
+}

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


[clang] [clang][Interp] Handle SizeOfPackExprs (PR #71929)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes



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


3 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+5) 
- (modified) clang/lib/AST/Interp/ByteCodeExprGen.h (+1) 
- (modified) clang/test/AST/Interp/functions.cpp (+7) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 15a717089660337..c8d3c1243fc1094 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1624,6 +1624,11 @@ bool 
ByteCodeExprGen::VisitCXXScalarValueInitExpr(
   return this->visitZeroInitializer(classifyPrim(Ty), Ty, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
+  return this->emitConst(E->getPackLength(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 83986d3dd579ed6..ec9b6bb1408453c 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -107,6 +107,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
+  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
diff --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 4bef9c2f7c0d1fa..ab562e70606b672 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -371,3 +371,10 @@ namespace Variadic {
   constexpr int (*VFP)(...) = variadic_function2;
   static_assert(VFP() == 12, "");
 }
+
+namespace Packs {
+  template
+  constexpr int foo() { return sizeof...(T); }
+  static_assert(foo() == 2, "");
+  static_assert(foo<>() == 0, "");
+}

``




https://github.com/llvm/llvm-project/pull/71929
___
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-10 Thread Owen Pan via cfe-commits

owenca wrote:

@Meinersbur thanks for the info!

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] [SVE2.1][Clang][LLVM]Add 128bits builtin in Clang and LLVM intrinisc (PR #71930)

2023-11-10 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-aarch64

@llvm/pr-subscribers-llvm-ir

Author: None (CarolineConcatto)


Changes

This patch implements the builtins in Clang
and the LLVM-IR intrinsic for the following:

EXTQ
// Variants are also available for:
// _s8, _s16, _u16, _s32, _u32, _s64, _u64
// _bf16, _f16, _f32, _f64
svuint8_t svextq_lane[_u8](svuint8_t zdn,

TBLQ and TBXQ
// Variants are also available for:
// _u8, _u16, _s16, _u32, _s32, _u64, _s64
// _bf16, _f16, _f32, _f64
svint8_t svtblq[_s8](svint8_t zn, svuint8_t zm);
svint8_t svtbxq[_s8](svint8_t zn, svuint8_t zm);

UZPQ1, UZPQ2, ZIPQ1 and ZIPQ2
// Variants are also available for:
// _s8, _u16, _s16, _u32, _s32, _u64, _s64
// _bf16, _f16, _f32, _f64
svuint8_t svuzpq1[_u8](svuint8_t zn, svuint8_t zm); svuint8_t 
svuzpq2[_u8](svuint8_t zn, svuint8_t zm); svuint8_t svzipq1[_u8](svuint8_t zn, 
svuint8_t zm); svuint8_t svzipq2[_u8](svuint8_t zn, svuint8_t zm);

PMOV
// Variants are available for:
// _s8, _u16, _s16, _s32, _u32, _s64, _u64
svbool_t svpmov_lane[_u8](svuint8_t zn, uint64_t imm); svbool_t 
svpmov[_u8](svuint8_t zn); // The immediate is zero svuint8_t 
svpmov_u8_z(svbool_t pn); // The immediate is zero

// Variants are available for:
// _s16, _s32, _u32, _s64, _u64
svuint16_t svpmov_lane[_u16]_m(svuint16_t zd, svbool_t pn, uint64_t imm);

According to the PR#257[1]
[1]ARM-software/acle#257

Co-author by: Hassnaa Hamdi 

---

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


26 Files Affected:

- (modified) clang/include/clang/Basic/arm_sve.td (+33) 
- (modified) clang/include/clang/Basic/arm_sve_sme_incl.td (+3) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+12) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_extq.c 
(+213) 
- (added) 
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_pmov_to_pred.c (+304) 
- (added) 
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_pmov_to_vector.c 
(+276) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_tblq.c 
(+214) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_tbxq.c 
(+214) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_uzpq1.c 
(+217) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_uzpq2.c 
(+216) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_zipq1.c 
(+217) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_zipq2.c 
(+217) 
- (modified) clang/test/Sema/aarch64-sve2p1-intrinsics/acle_sve2p1_imm.cpp (+6) 
- (modified) llvm/include/llvm/IR/IntrinsicsAArch64.td (+41) 
- (modified) llvm/lib/Target/AArch64/AArch64InstrFormats.td (+33) 
- (modified) llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td (+9-9) 
- (modified) llvm/lib/Target/AArch64/SVEInstrFormats.td (+80-6) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-extq.ll (+83) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-pmov-to-pred.ll (+121) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-pmov-to-vector.ll (+117) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-tblq.ll (+83) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-tbxq.ll (+83) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-uzpq1.ll (+85) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-uzpq2.ll (+85) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-zipq1.ll (+85) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-zipq2.ll (+85) 


``diff
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 3d4c2129565903d..c377a0b89c1d591 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1992,3 +1992,36 @@ let TargetGuard = "sme2" in {
   def SVADD_SINGLE_X2 : SInst<"svadd[_single_{d}_x2]", "22d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x2", [IsStreaming], []>;
   def SVADD_SINGLE_X4 : SInst<"svadd[_single_{d}_x4]", "44d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x4", [IsStreaming], []>;
 }
+
+let TargetGuard = "sve2p1" in {
+  // ZIPQ1, ZIPQ2, UZPQ1, UZPQ2
+  def SVZIPQ1 : SInst<"svzipq1[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_zipq1", [], []>;
+  def SVZIPQ2 : SInst<"svzipq2[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_zipq2", [], []>;
+  def SVUZPQ1 : SInst<"svuzpq1[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_uzpq1", [], []>;
+  def SVUZPQ2 : SInst<"svuzpq2[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_uzpq2", [], []>;
+  // TBLQ, TBXQ
+  def SVTBLQ : SInst<"svtblq[_{d}]", "ddu", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_tblq">;
+  def SVTBXQ : SInst<"svtbxq[_{d}]", "dddu", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_tbxq">;
+  // EXTQ
+  def EXTQ : SInst<"svextq_lane[_{d}]", "dddk", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_extq_lane", [], [ImmCheck<2, ImmCheck0_15>]>;
+  // PMOV
+  // Move to Pred
+  m

[clang] [llvm] [SVE2.1][Clang][LLVM]Add 128bits builtin in Clang and LLVM intrinisc (PR #71930)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (CarolineConcatto)


Changes

This patch implements the builtins in Clang
and the LLVM-IR intrinsic for the following:

EXTQ
// Variants are also available for:
// _s8, _s16, _u16, _s32, _u32, _s64, _u64
// _bf16, _f16, _f32, _f64
svuint8_t svextq_lane[_u8](svuint8_t zdn,

TBLQ and TBXQ
// Variants are also available for:
// _u8, _u16, _s16, _u32, _s32, _u64, _s64
// _bf16, _f16, _f32, _f64
svint8_t svtblq[_s8](svint8_t zn, svuint8_t zm);
svint8_t svtbxq[_s8](svint8_t zn, svuint8_t zm);

UZPQ1, UZPQ2, ZIPQ1 and ZIPQ2
// Variants are also available for:
// _s8, _u16, _s16, _u32, _s32, _u64, _s64
// _bf16, _f16, _f32, _f64
svuint8_t svuzpq1[_u8](svuint8_t zn, svuint8_t zm); svuint8_t 
svuzpq2[_u8](svuint8_t zn, svuint8_t zm); svuint8_t svzipq1[_u8](svuint8_t zn, 
svuint8_t zm); svuint8_t svzipq2[_u8](svuint8_t zn, svuint8_t zm);

PMOV
// Variants are available for:
// _s8, _u16, _s16, _s32, _u32, _s64, _u64
svbool_t svpmov_lane[_u8](svuint8_t zn, uint64_t imm); svbool_t 
svpmov[_u8](svuint8_t zn); // The immediate is zero svuint8_t 
svpmov_u8_z(svbool_t pn); // The immediate is zero

// Variants are available for:
// _s16, _s32, _u32, _s64, _u64
svuint16_t svpmov_lane[_u16]_m(svuint16_t zd, svbool_t pn, uint64_t imm);

According to the PR#257[1]
[1]ARM-software/acle#257

Co-author by: Hassnaa Hamdi 

---

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


26 Files Affected:

- (modified) clang/include/clang/Basic/arm_sve.td (+33) 
- (modified) clang/include/clang/Basic/arm_sve_sme_incl.td (+3) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+12) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_extq.c 
(+213) 
- (added) 
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_pmov_to_pred.c (+304) 
- (added) 
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_pmov_to_vector.c 
(+276) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_tblq.c 
(+214) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_tbxq.c 
(+214) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_uzpq1.c 
(+217) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_uzpq2.c 
(+216) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_zipq1.c 
(+217) 
- (added) clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_zipq2.c 
(+217) 
- (modified) clang/test/Sema/aarch64-sve2p1-intrinsics/acle_sve2p1_imm.cpp (+6) 
- (modified) llvm/include/llvm/IR/IntrinsicsAArch64.td (+41) 
- (modified) llvm/lib/Target/AArch64/AArch64InstrFormats.td (+33) 
- (modified) llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td (+9-9) 
- (modified) llvm/lib/Target/AArch64/SVEInstrFormats.td (+80-6) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-extq.ll (+83) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-pmov-to-pred.ll (+121) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-pmov-to-vector.ll (+117) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-tblq.ll (+83) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-tbxq.ll (+83) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-uzpq1.ll (+85) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-uzpq2.ll (+85) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-zipq1.ll (+85) 
- (added) llvm/test/CodeGen/AArch64/sve2p1-intrinsics-zipq2.ll (+85) 


``diff
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 3d4c2129565903d..c377a0b89c1d591 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1992,3 +1992,36 @@ let TargetGuard = "sme2" in {
   def SVADD_SINGLE_X2 : SInst<"svadd[_single_{d}_x2]", "22d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x2", [IsStreaming], []>;
   def SVADD_SINGLE_X4 : SInst<"svadd[_single_{d}_x4]", "44d", "cUcsUsiUilUl", 
MergeNone, "aarch64_sve_add_single_x4", [IsStreaming], []>;
 }
+
+let TargetGuard = "sve2p1" in {
+  // ZIPQ1, ZIPQ2, UZPQ1, UZPQ2
+  def SVZIPQ1 : SInst<"svzipq1[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_zipq1", [], []>;
+  def SVZIPQ2 : SInst<"svzipq2[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_zipq2", [], []>;
+  def SVUZPQ1 : SInst<"svuzpq1[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_uzpq1", [], []>;
+  def SVUZPQ2 : SInst<"svuzpq2[_{d}]", "ddd", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_uzpq2", [], []>;
+  // TBLQ, TBXQ
+  def SVTBLQ : SInst<"svtblq[_{d}]", "ddu", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_tblq">;
+  def SVTBXQ : SInst<"svtbxq[_{d}]", "dddu", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_tbxq">;
+  // EXTQ
+  def EXTQ : SInst<"svextq_lane[_{d}]", "dddk", "cUcsUsiUilUlbhfd", MergeNone, 
"aarch64_sve_extq_lane", [], [ImmCheck<2, ImmCheck0_15>]>;
+  // PMOV
+  // Move to Pred
+  multiclass PMOV_TO_PRED flags=[], ImmChe

[PATCH] D138846: MC/DC in LLVM Source-Based Code Coverage: LLVM back-end and compiler-rt

2023-11-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In D138846#4656594 , @hans wrote:

> Just a heads up that we're seeing crashes in the Rust compiler which bisects 
> to this change. Investigating in 
> https://bugs.chromium.org/p/chromium/issues/detail?id=1500558

Here's a small reproducer:

  $ cat /tmp/x.ll
  target triple = "x86_64-unknown-linux-gnu"
  
  declare void @llvm.instrprof.increment(ptr %0, i64 %1, i32 %2, i32 %3)
  @prof_name = private constant [9 x i8] c"prof_name"
  
  define internal void @f() {
call void @llvm.instrprof.increment(ptr @prof_name, i64 123456, i32 32, i32 
0)
ret void
  }
  
  define void @foo() {
call void @f()
ret void
  }
  
  define void @bar() {
call void @f()
ret void
  }
  
  $ build/bin/opt /tmp/x.ll -passes='cgscc(inline),instrprof' -S
  PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ 
and include the crash backtrace.
  Stack dump:
  0.  Program arguments: build/bin/opt /tmp/x.ll 
-passes=cgscc(inline),instrprof -S
   #0 0x55fcf4193d48 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(build/bin/opt+0x2f77d48)
   #1 0x55fcf419186e llvm::sys::RunSignalHandlers() 
(build/bin/opt+0x2f7586e)
   #2 0x55fcf41943fd SignalHandler(int) Signals.cpp:0:0
   #3 0x7f0cbe05a510 (/lib/x86_64-linux-gnu/libc.so.6+0x3c510)
   #4 0x55fcf3b279c9 llvm::GlobalVariable::eraseFromParent() 
(build/bin/opt+0x290b9c9)
   #5 0x55fcf47a87c8 llvm::InstrProfiling::emitNameData() 
(build/bin/opt+0x358c7c8)
   #6 0x55fcf47a32e3 llvm::InstrProfiling::run(llvm::Module&, 
std::function) 
(build/bin/opt+0x35872e3)
   #7 0x55fcf47a2b99 llvm::InstrProfiling::run(llvm::Module&, 
llvm::AnalysisManager&) (build/bin/opt+0x3586b99)
   #8 0x55fcf43a31ed llvm::detail::PassModel>::run(llvm::Module&, 
llvm::AnalysisManager&) (build/bin/opt+0x31871ed)
   #9 0x55fcf3bacf04 llvm::PassManager>::run(llvm::Module&, 
llvm::AnalysisManager&) (build/bin/opt+0x2990f04)
  #10 0x55fcf1b479db llvm::runPassPipeline(llvm::StringRef, llvm::Module&, 
llvm::TargetMachine*, llvm::TargetLibraryInfoImpl*, llvm::ToolOutputFile*, 
llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::StringRef, 
llvm::ArrayRef, llvm::opt_tool::OutputKind, 
llvm::opt_tool::VerifierKind, bool, bool, bool, bool, bool, bool, bool) 
(build/bin/opt+0x92b9db)
  #11 0x55fcf1b54e95 main (build/bin/opt+0x938e95)
  #12 0x7f0cbe0456ca __libc_start_call_main 
./csu/../sysdeps/nptl/libc_start_call_main.h:74:3
  #13 0x7f0cbe045785 call_init ./csu/../csu/libc-start.c:128:20
  #14 0x7f0cbe045785 __libc_start_main ./csu/../csu/libc-start.c:347:5
  #15 0x55fcf1b4156a _start (build/bin/opt+0x92556a)
  Segmentation fault


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138846

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


[clang] [llvm] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Tom Eccles via cfe-commits

https://github.com/tblah updated https://github.com/llvm/llvm-project/pull/71734

>From ac9c18ef7d286147fd1ae4a49efe343644d2ccd1 Mon Sep 17 00:00:00 2001
From: Tom Eccles 
Date: Tue, 7 Nov 2023 18:55:20 +
Subject: [PATCH 1/3] [flang] add fveclib flag

-fveclib= allows users to choose a vectorized libm so that loops
containing math functions can be vectorized.

This is implemented as much as possible in the same way as in clang.
The driver test in veclib.f90 is copied from the clang test.
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 34 +++
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/include/flang/Frontend/CodeGenOptions.h | 11 
 flang/lib/Frontend/CompilerInvocation.cpp | 29 ++
 flang/lib/Frontend/FrontendActions.cpp| 58 ---
 flang/test/Driver/driver-help-hidden.f90  |  1 +
 flang/test/Driver/driver-help.f90 |  2 +
 flang/test/Driver/fveclib-codegen.f90 | 13 +
 flang/test/Driver/fveclib.f90 | 30 ++
 10 files changed, 172 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Driver/fveclib-codegen.f90
 create mode 100644 flang/test/Driver/fveclib.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 36052511203f65c..f275ec68e710769 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3118,7 +3118,7 @@ def fno_global_isel : Flag<["-"], "fno-global-isel">, 
Group,
 def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, 
Group,
   Alias;
 def fveclib : Joined<["-"], "fveclib=">, Group,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
 HelpText<"Use the given vector functions library">,
 
Values<"Accelerate,libmvec,MASSV,SVML,SLEEF,Darwin_libsystem_m,ArmPL,none">,
 NormalizedValuesScope<"CodeGenOptions">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 999039f83ddfb92..b5ebbc4ef37e1db 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -232,6 +232,40 @@ void Flang::addTargetOptions(const ArgList &Args,
 break;
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
+StringRef Name = A->getValue();
+if (Name == "SVML") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "LIBMVEC-X86") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "SLEEF" || Name == "ArmPL") {
+  if (Triple.getArch() != llvm::Triple::aarch64 &&
+  Triple.getArch() != llvm::Triple::aarch64_be)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+}
+
+if (Triple.isOSDarwin()) {
+  // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
+  // here incase they are added someday
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+if (A->getValue() == StringRef{"Accelerate"}) {
+  CmdArgs.push_back("-framework");
+  CmdArgs.push_back("Accelerate");
+  A->render(Args, CmdArgs);
+}
+  }
+} else {
+  A->render(Args, CmdArgs);
+}
+  }
+
   // TODO: Add target specific flags, ABI, mtune option etc.
 }
 
diff --git a/flang/include/flang/Frontend/CodeGenOptions.def 
b/flang/include/flang/Frontend/CodeGenOptions.def
index 1e350869f1377e3..9d09ac1cbb251b1 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -37,6 +37,7 @@ CODEGENOPT(AliasAnalysis, 1, 0) ///< Enable alias analysis 
pass
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, llvm::Reloc::PIC_) 
///< Name of the relocation model to use.
 ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  
llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
+ENUM_CODEGENOPT(VecLib, VectorLibrary, 3, VectorLibrary::NoLibrary) ///< 
Vector functions library to use
 
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b0e0c91e09ab38f..1eb2264560a02fa 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -81,6 +81,17 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  enum class VectorLibrary {
+NoLibrary,  // Don't use any

[clang] [llvm] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Tom Eccles via cfe-commits

https://github.com/tblah updated https://github.com/llvm/llvm-project/pull/71734

>From ac9c18ef7d286147fd1ae4a49efe343644d2ccd1 Mon Sep 17 00:00:00 2001
From: Tom Eccles 
Date: Tue, 7 Nov 2023 18:55:20 +
Subject: [PATCH 1/4] [flang] add fveclib flag

-fveclib= allows users to choose a vectorized libm so that loops
containing math functions can be vectorized.

This is implemented as much as possible in the same way as in clang.
The driver test in veclib.f90 is copied from the clang test.
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 34 +++
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/include/flang/Frontend/CodeGenOptions.h | 11 
 flang/lib/Frontend/CompilerInvocation.cpp | 29 ++
 flang/lib/Frontend/FrontendActions.cpp| 58 ---
 flang/test/Driver/driver-help-hidden.f90  |  1 +
 flang/test/Driver/driver-help.f90 |  2 +
 flang/test/Driver/fveclib-codegen.f90 | 13 +
 flang/test/Driver/fveclib.f90 | 30 ++
 10 files changed, 172 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Driver/fveclib-codegen.f90
 create mode 100644 flang/test/Driver/fveclib.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 36052511203f65c..f275ec68e710769 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3118,7 +3118,7 @@ def fno_global_isel : Flag<["-"], "fno-global-isel">, 
Group,
 def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, 
Group,
   Alias;
 def fveclib : Joined<["-"], "fveclib=">, Group,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
 HelpText<"Use the given vector functions library">,
 
Values<"Accelerate,libmvec,MASSV,SVML,SLEEF,Darwin_libsystem_m,ArmPL,none">,
 NormalizedValuesScope<"CodeGenOptions">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 999039f83ddfb92..b5ebbc4ef37e1db 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -232,6 +232,40 @@ void Flang::addTargetOptions(const ArgList &Args,
 break;
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
+StringRef Name = A->getValue();
+if (Name == "SVML") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "LIBMVEC-X86") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "SLEEF" || Name == "ArmPL") {
+  if (Triple.getArch() != llvm::Triple::aarch64 &&
+  Triple.getArch() != llvm::Triple::aarch64_be)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+}
+
+if (Triple.isOSDarwin()) {
+  // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
+  // here incase they are added someday
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+if (A->getValue() == StringRef{"Accelerate"}) {
+  CmdArgs.push_back("-framework");
+  CmdArgs.push_back("Accelerate");
+  A->render(Args, CmdArgs);
+}
+  }
+} else {
+  A->render(Args, CmdArgs);
+}
+  }
+
   // TODO: Add target specific flags, ABI, mtune option etc.
 }
 
diff --git a/flang/include/flang/Frontend/CodeGenOptions.def 
b/flang/include/flang/Frontend/CodeGenOptions.def
index 1e350869f1377e3..9d09ac1cbb251b1 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -37,6 +37,7 @@ CODEGENOPT(AliasAnalysis, 1, 0) ///< Enable alias analysis 
pass
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, llvm::Reloc::PIC_) 
///< Name of the relocation model to use.
 ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  
llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
+ENUM_CODEGENOPT(VecLib, VectorLibrary, 3, VectorLibrary::NoLibrary) ///< 
Vector functions library to use
 
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b0e0c91e09ab38f..1eb2264560a02fa 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -81,6 +81,17 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  enum class VectorLibrary {
+NoLibrary,  // Don't use any

[clang] [llvm] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 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 76947e040545aa1cbaa27cf0b06fae9ced272ca4 
8265a5729a919e4ddb914b5322804b4c3290ee82 -- 
llvm/include/llvm/Frontend/Driver/CodeGenOptions.h 
llvm/lib/Frontend/Driver/CodeGenOptions.cpp 
clang/include/clang/Basic/CodeGenOptions.h clang/lib/CodeGen/BackendUtil.cpp 
clang/lib/Driver/ToolChains/Flang.cpp 
clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp 
flang/include/flang/Frontend/CodeGenOptions.h 
flang/lib/Frontend/CompilerInvocation.cpp flang/lib/Frontend/FrontendActions.cpp
``





View the diff from clang-format here.


``diff
diff --git a/flang/lib/Frontend/FrontendActions.cpp 
b/flang/lib/Frontend/FrontendActions.cpp
index e3550b34ec80..d7ca7b66584d 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -852,9 +852,12 @@ getOutputStream(CompilerInstance &ci, llvm::StringRef 
inFile,
 /// \param [in] llvmModule LLVM module to lower to assembly/machine-code
 /// \param [in] codeGenOpts options configuring codegen pipeline
 /// \param [out] os Output stream to emit the generated code to
-static void generateMachineCodeOrAssemblyImpl(
-clang::DiagnosticsEngine &diags, llvm::TargetMachine &tm,
-BackendActionTy act, llvm::Module &llvmModule, const CodeGenOptions 
&codeGenOpts, llvm::raw_pwrite_stream &os) {
+static void generateMachineCodeOrAssemblyImpl(clang::DiagnosticsEngine &diags,
+  llvm::TargetMachine &tm,
+  BackendActionTy act,
+  llvm::Module &llvmModule,
+  const CodeGenOptions 
&codeGenOpts,
+  llvm::raw_pwrite_stream &os) {
   assert(((act == BackendActionTy::Backend_EmitObj) ||
   (act == BackendActionTy::Backend_EmitAssembly)) &&
  "Unsupported action");

``




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


[clang] [clang][TSA] Make RequiresCapability a DeclOrType attribute (PR #67095)

2023-11-10 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 



@@ -1894,6 +1894,8 @@ void TypePrinter::printAttributedAfter(const 
AttributedType *T,
   case attr::ArmMveStrictPolymorphism:
 OS << "__clang_arm_mve_strict_polymorphism";
 break;
+  case attr::RequiresCapability:
+OS << "requires_capability(blah)";

tbaederr wrote:

>From looking at this some more, it seems like the type doesn't save an actual 
>`Attr`?

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


[clang-tools-extra] [llvm] [clang] [AMDGPU] Fix GCNUpwardRPTracker. (WIP) (PR #71186)

2023-11-10 Thread Valery Pykhtin via cfe-commits

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


[clang-tools-extra] ec095b7 - [clangd] Fix builds after 0255b217c3766ce0aa23bd4fb050b447be2a1d26

2023-11-10 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-11-10T13:55:43+01:00
New Revision: ec095b74243bf5db2a70961ecbbde2a30efdccce

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

LOG: [clangd] Fix builds after 0255b217c3766ce0aa23bd4fb050b447be2a1d26

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp
index 357af8c9b679a99..e36b3249bc7b929 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ScopifyEnum.cpp
@@ -7,15 +7,28 @@
 
//===--===//
 
 #include "ParsedAST.h"
+#include "Protocol.h"
+#include "Selection.h"
+#include "SourceCode.h"
 #include "XRefs.h"
 #include "refactor/Tweak.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/MemoryBuffer.h"
 
+#include 
 #include 
+#include 
+#include 
+#include 
 
 namespace clang::clangd {
 namespace {
@@ -87,9 +100,9 @@ Expected ScopifyEnum::apply(const Selection 
&Inputs) {

SM->getBufferData(SM->getMainFileID(;
 
   if (auto Err = addClassKeywordToDeclarations())
-return Err;
+return std::move(Err);
   if (auto Err = scopifyEnumValues())
-return Err;
+return std::move(Err);
 
   return E;
 }



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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;

egorzhdan wrote:

Done

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan updated 
https://github.com/llvm/llvm-project/pull/71413

>From f80d68edf0787821531c0f88d845b253703ef13e Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Mon, 6 Nov 2023 15:41:19 +
Subject: [PATCH 1/2] [APINotes] NFC: rename `StoredObjCSelector::NumPieces`

This value actually represents a number of arguments the selector takes, not 
the number of identifiers. These will be different if the selector takes no 
arguments.
---
 clang/lib/APINotes/APINotesFormat.h   | 6 +++---
 clang/lib/APINotes/APINotesReader.cpp | 2 +-
 clang/lib/APINotes/APINotesWriter.cpp | 2 +-
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/lib/APINotes/APINotesFormat.h 
b/clang/lib/APINotes/APINotesFormat.h
index 5897b45d3796d0e..615314c46f09cac 100644
--- a/clang/lib/APINotes/APINotesFormat.h
+++ b/clang/lib/APINotes/APINotesFormat.h
@@ -247,7 +247,7 @@ using EnumConstantDataLayout =
 
 /// A stored Objective-C selector.
 struct StoredObjCSelector {
-  unsigned NumPieces;
+  unsigned NumArgs;
   llvm::SmallVector Identifiers;
 };
 
@@ -302,7 +302,7 @@ template <> struct 
DenseMapInfo {
 
   static unsigned
   getHashValue(const clang::api_notes::StoredObjCSelector &Selector) {
-auto hash = llvm::hash_value(Selector.NumPieces);
+auto hash = llvm::hash_value(Selector.NumArgs);
 hash = hash_combine(hash, Selector.Identifiers.size());
 for (auto piece : Selector.Identifiers)
   hash = hash_combine(hash, static_cast(piece));
@@ -313,7 +313,7 @@ template <> struct 
DenseMapInfo {
 
   static bool isEqual(const clang::api_notes::StoredObjCSelector &LHS,
   const clang::api_notes::StoredObjCSelector &RHS) {
-return LHS.NumPieces == RHS.NumPieces && LHS.Identifiers == 
RHS.Identifiers;
+return LHS.NumArgs == RHS.NumArgs && LHS.Identifiers == RHS.Identifiers;
   }
 };
 
diff --git a/clang/lib/APINotes/APINotesReader.cpp 
b/clang/lib/APINotes/APINotesReader.cpp
index 2cbf5fd3bf50301..01177b9b1d04dde 100644
--- a/clang/lib/APINotes/APINotesReader.cpp
+++ b/clang/lib/APINotes/APINotesReader.cpp
@@ -421,7 +421,7 @@ class ObjCSelectorTableInfo {
 
   static internal_key_type ReadKey(const uint8_t *Data, unsigned Length) {
 internal_key_type Key;
-Key.NumPieces =
+Key.NumArgs =
 endian::readNext(Data);
 unsigned NumIdents = (Length - sizeof(uint16_t)) / sizeof(uint32_t);
 for (unsigned i = 0; i != NumIdents; ++i) {
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index 770d78e22050c01..62a2ab1799913a1 100644
--- a/clang/lib/APINotes/APINotesWriter.cpp
+++ b/clang/lib/APINotes/APINotesWriter.cpp
@@ -823,7 +823,7 @@ class ObjCSelectorTableInfo {
 
   void EmitKey(raw_ostream &OS, key_type_ref Key, unsigned) {
 llvm::support::endian::Writer writer(OS, llvm::endianness::little);
-writer.write(Key.NumPieces);
+writer.write(Key.NumArgs);
 for (auto Identifier : Key.Identifiers)
   writer.write(Identifier);
   }

>From 912092a4a8a815b4b6b449842cb028f564f829f6 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Mon, 6 Nov 2023 15:45:11 +
Subject: [PATCH 2/2] [APINotes] Upstream APINotes YAML compiler

This upstreams more of the Clang API Notes functionality that is currently 
implemented in the Apple fork: 
https://github.com/apple/llvm-project/tree/next/clang/lib/APINotes
---
 .../clang/APINotes/APINotesYAMLCompiler.h |  11 +
 clang/include/clang/APINotes/Types.h  |   1 +
 clang/lib/APINotes/APINotesReader.cpp |   1 +
 clang/lib/APINotes/APINotesYAMLCompiler.cpp   | 479 +-
 4 files changed, 491 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/APINotes/APINotesYAMLCompiler.h 
b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
index 6098d0ee36fc477..9c24ed85b6a124a 100644
--- a/clang/include/clang/APINotes/APINotesYAMLCompiler.h
+++ b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
@@ -10,14 +10,25 @@
 #define LLVM_CLANG_APINOTES_APINOTESYAMLCOMPILER_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/raw_ostream.h"
 
+namespace clang {
+class FileEntry;
+} // namespace clang
+
 namespace clang {
 namespace api_notes {
 /// Parses the APINotes YAML content and writes the representation back to the
 /// specified stream.  This provides a means of testing the YAML processing of
 /// the APINotes format.
 bool parseAndDumpAPINotes(llvm::StringRef YI, llvm::raw_ostream &OS);
+
+/// Converts API notes from YAML format to binary format.
+bool compileAPINotes(llvm::StringRef YAMLInput, const FileEntry *SourceFile,
+ llvm::raw_ostream &OS,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr,
+ void *DiagHandlerCtxt = nullptr);
 } // namespace api_notes
 } // namespace clang
 
diff --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index b74244bc8f1cbd3..79595abcf7d02d9 100644
--

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{

egorzhdan wrote:

Alright, done

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;

egorzhdan wrote:

Don't think there is a good reason, removed the return type

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }

egorzhdan wrote:

This underflows `offset`, but I simplified this bit of code another way by 
using `resize`

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,

egorzhdan wrote:

Done

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,

egorzhdan wrote:

Makes sense, renamed it

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;

egorzhdan wrote:

Done

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;

egorzhdan wrote:

Done

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +

egorzhdan wrote:

Done

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;
+selectorRef.NumArgs = !takesArguments ? 0 : a.size();
+selectorRef.Identifiers = a;
+
+// Translate the initializer info.
+MInfo.DesignatedInit = TheMethod.DesignatedInit;
+MInfo.RequiredInit = TheMethod.Required;
+if (TheMethod.FactoryAsInit != FactoryAsInitKind::Infer) {
+  emitError("'Fact

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;
+selectorRef.NumArgs = !takesArguments ? 0 : a.size();
+selectorRef.Identifiers = a;
+
+// Translate the initializer info.
+MInfo.DesignatedInit = TheMethod.DesignatedInit;
+MInfo.RequiredInit = TheMethod.Required;
+if (TheMethod.FactoryAsInit != FactoryAsInitKind::Infer) {
+  emitError("'Fact

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;
+selectorRef.NumArgs = !takesArguments ? 0 : a.size();
+selectorRef.Identifiers = a;
+
+// Translate the initializer info.
+MInfo.DesignatedInit = TheMethod.DesignatedInit;
+MInfo.RequiredInit = TheMethod.Required;
+if (TheMethod.FactoryAsInit != FactoryAsInitKind::Infer) {
+  emitError("'Fact

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;
+selectorRef.NumArgs = !takesArguments ? 0 : a.size();
+selectorRef.Identifiers = a;
+
+// Translate the initializer info.
+MInfo.DesignatedInit = TheMethod.DesignatedInit;
+MInfo.RequiredInit = TheMethod.Required;
+if (TheMethod.FactoryAsInit != FactoryAsInitKind::Infer) {
+  emitError("'Fact

[llvm] [clang] [flang] [flang] add fveclib flag (PR #71734)

2023-11-10 Thread Tom Eccles via cfe-commits

https://github.com/tblah updated https://github.com/llvm/llvm-project/pull/71734

>From ac9c18ef7d286147fd1ae4a49efe343644d2ccd1 Mon Sep 17 00:00:00 2001
From: Tom Eccles 
Date: Tue, 7 Nov 2023 18:55:20 +
Subject: [PATCH 1/4] [flang] add fveclib flag

-fveclib= allows users to choose a vectorized libm so that loops
containing math functions can be vectorized.

This is implemented as much as possible in the same way as in clang.
The driver test in veclib.f90 is copied from the clang test.
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 34 +++
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/include/flang/Frontend/CodeGenOptions.h | 11 
 flang/lib/Frontend/CompilerInvocation.cpp | 29 ++
 flang/lib/Frontend/FrontendActions.cpp| 58 ---
 flang/test/Driver/driver-help-hidden.f90  |  1 +
 flang/test/Driver/driver-help.f90 |  2 +
 flang/test/Driver/fveclib-codegen.f90 | 13 +
 flang/test/Driver/fveclib.f90 | 30 ++
 10 files changed, 172 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Driver/fveclib-codegen.f90
 create mode 100644 flang/test/Driver/fveclib.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 36052511203f65c..f275ec68e710769 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3118,7 +3118,7 @@ def fno_global_isel : Flag<["-"], "fno-global-isel">, 
Group,
 def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, 
Group,
   Alias;
 def fveclib : Joined<["-"], "fveclib=">, Group,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
 HelpText<"Use the given vector functions library">,
 
Values<"Accelerate,libmvec,MASSV,SVML,SLEEF,Darwin_libsystem_m,ArmPL,none">,
 NormalizedValuesScope<"CodeGenOptions">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 999039f83ddfb92..b5ebbc4ef37e1db 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -232,6 +232,40 @@ void Flang::addTargetOptions(const ArgList &Args,
 break;
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
+StringRef Name = A->getValue();
+if (Name == "SVML") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "LIBMVEC-X86") {
+  if (Triple.getArch() != llvm::Triple::x86 &&
+  Triple.getArch() != llvm::Triple::x86_64)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+} else if (Name == "SLEEF" || Name == "ArmPL") {
+  if (Triple.getArch() != llvm::Triple::aarch64 &&
+  Triple.getArch() != llvm::Triple::aarch64_be)
+D.Diag(diag::err_drv_unsupported_opt_for_target)
+<< Name << Triple.getArchName();
+}
+
+if (Triple.isOSDarwin()) {
+  // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
+  // here incase they are added someday
+  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+if (A->getValue() == StringRef{"Accelerate"}) {
+  CmdArgs.push_back("-framework");
+  CmdArgs.push_back("Accelerate");
+  A->render(Args, CmdArgs);
+}
+  }
+} else {
+  A->render(Args, CmdArgs);
+}
+  }
+
   // TODO: Add target specific flags, ABI, mtune option etc.
 }
 
diff --git a/flang/include/flang/Frontend/CodeGenOptions.def 
b/flang/include/flang/Frontend/CodeGenOptions.def
index 1e350869f1377e3..9d09ac1cbb251b1 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -37,6 +37,7 @@ CODEGENOPT(AliasAnalysis, 1, 0) ///< Enable alias analysis 
pass
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, llvm::Reloc::PIC_) 
///< Name of the relocation model to use.
 ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  
llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
+ENUM_CODEGENOPT(VecLib, VectorLibrary, 3, VectorLibrary::NoLibrary) ///< 
Vector functions library to use
 
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
diff --git a/flang/include/flang/Frontend/CodeGenOptions.h 
b/flang/include/flang/Frontend/CodeGenOptions.h
index b0e0c91e09ab38f..1eb2264560a02fa 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.h
+++ b/flang/include/flang/Frontend/CodeGenOptions.h
@@ -81,6 +81,17 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  enum class VectorLibrary {
+NoLibrary,  // Don't use any

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");

egorzhdan wrote:

This has two usages below

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}

egorzhdan wrote:

Looks better indeed, thanks!

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,

egorzhdan wrote:

Done

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


[clang] [clang-tools-extra] [llvm] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71935)

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

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

Also fixed a bug in `isStartOfName()` and cleaned up some old test cases.

Fixed #71563.

This is a rework of #71755.

>From 17921d5a1d74017128691428815ede53ac1a4d67 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 8 Nov 2023 17:55:56 -0800
Subject: [PATCH 1/3] [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;
   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 &Current,
   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 

[clang] [clang-tools-extra] [llvm] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71935)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Owen Pan (owenca)


Changes

Also fixed a bug in `isStartOfName()` and cleaned up some old test cases.

Fixed #71563.

This is a rework of #71755.

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


4 Files Affected:

- (modified) clang/docs/ClangFormatStyleOptions.rst (+11-2) 
- (modified) clang/include/clang/Format/Format.h (+11-2) 
- (modified) clang/lib/Format/TokenAnnotator.cpp (+25-8) 
- (modified) clang/unittests/Format/FormatTest.cpp (+28-13) 


``diff
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 d648e441f23fe9e..725f02a37581d24 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1997,6 +1997,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = &Current;
   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
@@ -2184,6 +2188,11 @@ class AnnotatingParser {
 if (Tok.isNot(tok::identifier) || !Tok.Previous)
   return false;
 
+if (const auto *NextNonComment = Tok.getNextNonComment();
+!NextNonComment || NextNonComment->isPointerOrReference()) {
+  return false;
+}
+
 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
   Keywords.kw_as)) {
   return false;
@@ -3438,10 +3447,15 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
   if (AlignArrayOfStructures)
 

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;

egorzhdan wrote:

I renamed this to follow the upper-case conventions, would you prefer a 
different name? What does `seller` stand for?

https://github.com/llvm/llvm-project/pull/71413
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;
+selectorRef.NumArgs = !takesArguments ? 0 : a.size();
+selectorRef.Identifiers = a;
+
+// Translate the initializer info.
+MInfo.DesignatedInit = TheMethod.DesignatedInit;
+MInfo.RequiredInit = TheMethod.Required;
+if (TheMethod.FactoryAsInit != FactoryAsInitKind::Infer) {
+  emitError("'Fact

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan updated 
https://github.com/llvm/llvm-project/pull/71413

>From f80d68edf0787821531c0f88d845b253703ef13e Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Mon, 6 Nov 2023 15:41:19 +
Subject: [PATCH 1/2] [APINotes] NFC: rename `StoredObjCSelector::NumPieces`

This value actually represents a number of arguments the selector takes, not 
the number of identifiers. These will be different if the selector takes no 
arguments.
---
 clang/lib/APINotes/APINotesFormat.h   | 6 +++---
 clang/lib/APINotes/APINotesReader.cpp | 2 +-
 clang/lib/APINotes/APINotesWriter.cpp | 2 +-
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/lib/APINotes/APINotesFormat.h 
b/clang/lib/APINotes/APINotesFormat.h
index 5897b45d3796d0e..615314c46f09cac 100644
--- a/clang/lib/APINotes/APINotesFormat.h
+++ b/clang/lib/APINotes/APINotesFormat.h
@@ -247,7 +247,7 @@ using EnumConstantDataLayout =
 
 /// A stored Objective-C selector.
 struct StoredObjCSelector {
-  unsigned NumPieces;
+  unsigned NumArgs;
   llvm::SmallVector Identifiers;
 };
 
@@ -302,7 +302,7 @@ template <> struct 
DenseMapInfo {
 
   static unsigned
   getHashValue(const clang::api_notes::StoredObjCSelector &Selector) {
-auto hash = llvm::hash_value(Selector.NumPieces);
+auto hash = llvm::hash_value(Selector.NumArgs);
 hash = hash_combine(hash, Selector.Identifiers.size());
 for (auto piece : Selector.Identifiers)
   hash = hash_combine(hash, static_cast(piece));
@@ -313,7 +313,7 @@ template <> struct 
DenseMapInfo {
 
   static bool isEqual(const clang::api_notes::StoredObjCSelector &LHS,
   const clang::api_notes::StoredObjCSelector &RHS) {
-return LHS.NumPieces == RHS.NumPieces && LHS.Identifiers == 
RHS.Identifiers;
+return LHS.NumArgs == RHS.NumArgs && LHS.Identifiers == RHS.Identifiers;
   }
 };
 
diff --git a/clang/lib/APINotes/APINotesReader.cpp 
b/clang/lib/APINotes/APINotesReader.cpp
index 2cbf5fd3bf50301..01177b9b1d04dde 100644
--- a/clang/lib/APINotes/APINotesReader.cpp
+++ b/clang/lib/APINotes/APINotesReader.cpp
@@ -421,7 +421,7 @@ class ObjCSelectorTableInfo {
 
   static internal_key_type ReadKey(const uint8_t *Data, unsigned Length) {
 internal_key_type Key;
-Key.NumPieces =
+Key.NumArgs =
 endian::readNext(Data);
 unsigned NumIdents = (Length - sizeof(uint16_t)) / sizeof(uint32_t);
 for (unsigned i = 0; i != NumIdents; ++i) {
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index 770d78e22050c01..62a2ab1799913a1 100644
--- a/clang/lib/APINotes/APINotesWriter.cpp
+++ b/clang/lib/APINotes/APINotesWriter.cpp
@@ -823,7 +823,7 @@ class ObjCSelectorTableInfo {
 
   void EmitKey(raw_ostream &OS, key_type_ref Key, unsigned) {
 llvm::support::endian::Writer writer(OS, llvm::endianness::little);
-writer.write(Key.NumPieces);
+writer.write(Key.NumArgs);
 for (auto Identifier : Key.Identifiers)
   writer.write(Identifier);
   }

>From a95d72d013f31511350fb263c27afbc41ff7744b Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Mon, 6 Nov 2023 15:45:11 +
Subject: [PATCH 2/2] [APINotes] Upstream APINotes YAML compiler

This upstreams more of the Clang API Notes functionality that is currently 
implemented in the Apple fork: 
https://github.com/apple/llvm-project/tree/next/clang/lib/APINotes
---
 .../clang/APINotes/APINotesYAMLCompiler.h |  11 +
 clang/include/clang/APINotes/Types.h  |   1 +
 clang/lib/APINotes/APINotesReader.cpp |   1 +
 clang/lib/APINotes/APINotesYAMLCompiler.cpp   | 474 +-
 4 files changed, 486 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/APINotes/APINotesYAMLCompiler.h 
b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
index 6098d0ee36fc477..9c24ed85b6a124a 100644
--- a/clang/include/clang/APINotes/APINotesYAMLCompiler.h
+++ b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
@@ -10,14 +10,25 @@
 #define LLVM_CLANG_APINOTES_APINOTESYAMLCOMPILER_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/raw_ostream.h"
 
+namespace clang {
+class FileEntry;
+} // namespace clang
+
 namespace clang {
 namespace api_notes {
 /// Parses the APINotes YAML content and writes the representation back to the
 /// specified stream.  This provides a means of testing the YAML processing of
 /// the APINotes format.
 bool parseAndDumpAPINotes(llvm::StringRef YI, llvm::raw_ostream &OS);
+
+/// Converts API notes from YAML format to binary format.
+bool compileAPINotes(llvm::StringRef YAMLInput, const FileEntry *SourceFile,
+ llvm::raw_ostream &OS,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr,
+ void *DiagHandlerCtxt = nullptr);
 } // namespace api_notes
 } // namespace clang
 
diff --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index b74244bc8f1cbd3..79595abcf7d02d9 100644
--

[clang] [Clang][SME2] Add single and multi min and max builtins (PR #71688)

2023-11-10 Thread Sam Tebbs via cfe-commits

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


[clang] [Clang][SME2] Add single and multi min/max by vector builtins (PR #71707)

2023-11-10 Thread Sam Tebbs via cfe-commits

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


[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan updated 
https://github.com/llvm/llvm-project/pull/71413

>From f80d68edf0787821531c0f88d845b253703ef13e Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Mon, 6 Nov 2023 15:41:19 +
Subject: [PATCH 1/2] [APINotes] NFC: rename `StoredObjCSelector::NumPieces`

This value actually represents a number of arguments the selector takes, not 
the number of identifiers. These will be different if the selector takes no 
arguments.
---
 clang/lib/APINotes/APINotesFormat.h   | 6 +++---
 clang/lib/APINotes/APINotesReader.cpp | 2 +-
 clang/lib/APINotes/APINotesWriter.cpp | 2 +-
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/lib/APINotes/APINotesFormat.h 
b/clang/lib/APINotes/APINotesFormat.h
index 5897b45d3796d0e..615314c46f09cac 100644
--- a/clang/lib/APINotes/APINotesFormat.h
+++ b/clang/lib/APINotes/APINotesFormat.h
@@ -247,7 +247,7 @@ using EnumConstantDataLayout =
 
 /// A stored Objective-C selector.
 struct StoredObjCSelector {
-  unsigned NumPieces;
+  unsigned NumArgs;
   llvm::SmallVector Identifiers;
 };
 
@@ -302,7 +302,7 @@ template <> struct 
DenseMapInfo {
 
   static unsigned
   getHashValue(const clang::api_notes::StoredObjCSelector &Selector) {
-auto hash = llvm::hash_value(Selector.NumPieces);
+auto hash = llvm::hash_value(Selector.NumArgs);
 hash = hash_combine(hash, Selector.Identifiers.size());
 for (auto piece : Selector.Identifiers)
   hash = hash_combine(hash, static_cast(piece));
@@ -313,7 +313,7 @@ template <> struct 
DenseMapInfo {
 
   static bool isEqual(const clang::api_notes::StoredObjCSelector &LHS,
   const clang::api_notes::StoredObjCSelector &RHS) {
-return LHS.NumPieces == RHS.NumPieces && LHS.Identifiers == 
RHS.Identifiers;
+return LHS.NumArgs == RHS.NumArgs && LHS.Identifiers == RHS.Identifiers;
   }
 };
 
diff --git a/clang/lib/APINotes/APINotesReader.cpp 
b/clang/lib/APINotes/APINotesReader.cpp
index 2cbf5fd3bf50301..01177b9b1d04dde 100644
--- a/clang/lib/APINotes/APINotesReader.cpp
+++ b/clang/lib/APINotes/APINotesReader.cpp
@@ -421,7 +421,7 @@ class ObjCSelectorTableInfo {
 
   static internal_key_type ReadKey(const uint8_t *Data, unsigned Length) {
 internal_key_type Key;
-Key.NumPieces =
+Key.NumArgs =
 endian::readNext(Data);
 unsigned NumIdents = (Length - sizeof(uint16_t)) / sizeof(uint32_t);
 for (unsigned i = 0; i != NumIdents; ++i) {
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index 770d78e22050c01..62a2ab1799913a1 100644
--- a/clang/lib/APINotes/APINotesWriter.cpp
+++ b/clang/lib/APINotes/APINotesWriter.cpp
@@ -823,7 +823,7 @@ class ObjCSelectorTableInfo {
 
   void EmitKey(raw_ostream &OS, key_type_ref Key, unsigned) {
 llvm::support::endian::Writer writer(OS, llvm::endianness::little);
-writer.write(Key.NumPieces);
+writer.write(Key.NumArgs);
 for (auto Identifier : Key.Identifiers)
   writer.write(Identifier);
   }

>From 59c1842e8c3ba87138186f089faf7218f8568455 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Mon, 6 Nov 2023 15:45:11 +
Subject: [PATCH 2/2] [APINotes] Upstream APINotes YAML compiler

This upstreams more of the Clang API Notes functionality that is currently 
implemented in the Apple fork: 
https://github.com/apple/llvm-project/tree/next/clang/lib/APINotes
---
 .../clang/APINotes/APINotesYAMLCompiler.h |  11 +
 clang/include/clang/APINotes/Types.h  |   1 +
 clang/lib/APINotes/APINotesReader.cpp |   1 +
 clang/lib/APINotes/APINotesYAMLCompiler.cpp   | 480 +-
 4 files changed, 492 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/APINotes/APINotesYAMLCompiler.h 
b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
index 6098d0ee36fc477..9c24ed85b6a124a 100644
--- a/clang/include/clang/APINotes/APINotesYAMLCompiler.h
+++ b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
@@ -10,14 +10,25 @@
 #define LLVM_CLANG_APINOTES_APINOTESYAMLCOMPILER_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/raw_ostream.h"
 
+namespace clang {
+class FileEntry;
+} // namespace clang
+
 namespace clang {
 namespace api_notes {
 /// Parses the APINotes YAML content and writes the representation back to the
 /// specified stream.  This provides a means of testing the YAML processing of
 /// the APINotes format.
 bool parseAndDumpAPINotes(llvm::StringRef YI, llvm::raw_ostream &OS);
+
+/// Converts API notes from YAML format to binary format.
+bool compileAPINotes(llvm::StringRef YAMLInput, const FileEntry *SourceFile,
+ llvm::raw_ostream &OS,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr,
+ void *DiagHandlerCtxt = nullptr);
 } // namespace api_notes
 } // namespace clang
 
diff --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index b74244bc8f1cbd3..79595abcf7d02d9 100644
--

[clang] [APINotes] Upstream APINotes YAML compiler (PR #71413)

2023-11-10 Thread Egor Zhdan via cfe-commits


@@ -635,3 +638,496 @@ bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
 
   return false;
 }
+
+namespace {
+using namespace api_notes;
+
+class YAMLConverter {
+  const Module &TheModule;
+  APINotesWriter Writer;
+  llvm::raw_ostream &OS;
+  llvm::SourceMgr::DiagHandlerTy DiagHandler;
+  void *DiagHandlerCtxt;
+  bool ErrorOccured;
+
+  /// Emit a diagnostic
+  bool emitError(llvm::Twine Message) {
+DiagHandler(
+llvm::SMDiagnostic("", llvm::SourceMgr::DK_Error, Message.str()),
+DiagHandlerCtxt);
+ErrorOccured = true;
+return true;
+  }
+
+public:
+  YAMLConverter(const Module &TheModule, const FileEntry *SourceFile,
+llvm::raw_ostream &OS,
+llvm::SourceMgr::DiagHandlerTy DiagHandler,
+void *DiagHandlerCtxt)
+  : TheModule(TheModule), Writer(TheModule.Name, SourceFile), OS(OS),
+DiagHandler(DiagHandler), DiagHandlerCtxt(DiagHandlerCtxt),
+ErrorOccured(false) {}
+
+  bool convertAvailability(const AvailabilityItem &In,
+   CommonEntityInfo &OutInfo, llvm::StringRef APIName) 
{
+// Populate the unavailability information.
+OutInfo.Unavailable = (In.Mode == APIAvailability::None);
+OutInfo.UnavailableInSwift = (In.Mode == APIAvailability::NonSwift);
+if (OutInfo.Unavailable || OutInfo.UnavailableInSwift) {
+  OutInfo.UnavailableMsg = std::string(In.Msg);
+} else {
+  if (!In.Msg.empty()) {
+emitError("availability message for available API '" + APIName +
+  "' will not be used");
+  }
+}
+return false;
+  }
+
+  void convertParams(const ParamsSeq &Params, FunctionInfo &OutInfo) {
+for (const auto &P : Params) {
+  ParamInfo PI;
+  if (P.Nullability)
+PI.setNullabilityAudited(*P.Nullability);
+  PI.setNoEscape(P.NoEscape);
+  PI.setType(std::string(P.Type));
+  PI.setRetainCountConvention(P.RetainCountConvention);
+  while (OutInfo.Params.size() <= P.Position) {
+OutInfo.Params.push_back(ParamInfo());
+  }
+  OutInfo.Params[P.Position] |= PI;
+}
+  }
+
+  void convertNullability(const NullabilitySeq &Nullability,
+  std::optional NullabilityOfRet,
+  FunctionInfo &OutInfo, llvm::StringRef APIName) {
+if (Nullability.size() > FunctionInfo::getMaxNullabilityIndex()) {
+  emitError("nullability info for " + APIName + " does not fit");
+  return;
+}
+
+bool audited = false;
+unsigned int idx = 1;
+for (auto i = Nullability.begin(), e = Nullability.end(); i != e;
+ ++i, ++idx) {
+  OutInfo.addTypeInfo(idx, *i);
+  audited = true;
+}
+if (NullabilityOfRet) {
+  OutInfo.addTypeInfo(0, *NullabilityOfRet);
+  audited = true;
+} else if (audited) {
+  OutInfo.addTypeInfo(0, NullabilityKind::NonNull);
+}
+if (audited) {
+  OutInfo.NullabilityAudited = audited;
+  OutInfo.NumAdjustedNullable = idx;
+}
+  }
+
+  /// Convert the common parts of an entity from YAML.
+  template 
+  bool convertCommon(const T &Common, CommonEntityInfo &Info,
+ StringRef APIName) {
+convertAvailability(Common.Availability, Info, APIName);
+Info.setSwiftPrivate(Common.SwiftPrivate);
+Info.SwiftName = std::string(Common.SwiftName);
+return false;
+  }
+
+  /// Convert the common parts of a type entity from YAML.
+  template 
+  bool convertCommonType(const T &Common, CommonTypeInfo &Info,
+ StringRef APIName) {
+if (convertCommon(Common, Info, APIName))
+  return true;
+
+if (Common.SwiftBridge)
+  Info.setSwiftBridge(std::string(*Common.SwiftBridge));
+Info.setNSErrorDomain(Common.NSErrorDomain);
+return false;
+  }
+
+  // Translate from Method into ObjCMethodInfo and write it out.
+  void convertMethod(const Method &TheMethod, ContextID ClassID,
+ StringRef ClassName, VersionTuple SwiftVersion) {
+ObjCMethodInfo MInfo;
+
+if (convertCommon(TheMethod, MInfo, TheMethod.Selector))
+  return;
+
+// Check if the selector ends with ':' to determine if it takes arguments.
+bool takesArguments = TheMethod.Selector.endswith(":");
+
+// Split the selector into pieces.
+llvm::SmallVector a;
+TheMethod.Selector.split(a, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+if (!takesArguments && a.size() > 1) {
+  emitError("selector " + TheMethod.Selector +
+"is missing a ':' at the end");
+  return;
+}
+
+// Construct ObjCSelectorRef.
+api_notes::ObjCSelectorRef selectorRef;
+selectorRef.NumArgs = !takesArguments ? 0 : a.size();
+selectorRef.Identifiers = a;
+
+// Translate the initializer info.
+MInfo.DesignatedInit = TheMethod.DesignatedInit;
+MInfo.RequiredInit = TheMethod.Required;
+if (TheMethod.FactoryAsInit != FactoryAsInitKind::Infer) {
+  emitError("'Fact

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

2023-11-10 Thread Tobias Hieta via cfe-commits

tru wrote:

@tomekpaszek do you plan to finish this PR? we have been testing it internally 
on our code and would really like this to land in upstream LLVM.

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


[llvm] [clang] [AArch64][SME2] Add ldr_zt, str_zt builtins and intrinsics (PR #71795)

2023-11-10 Thread Matthew Devereau via cfe-commits

https://github.com/MDevereau updated 
https://github.com/llvm/llvm-project/pull/71795

>From 9846bc9efd79e6e3c2662ea42367c102df88799d Mon Sep 17 00:00:00 2001
From: Matt Devereau 
Date: Thu, 9 Nov 2023 10:50:05 +
Subject: [PATCH 1/4] [AArch64][SME2] Add ldr_zt, str_zt builtins and
 intrinsics

Adds the builtins:

void svldr_zt(uint64_t zt, const void *rn)
void svstr_zt(uint64_t zt, void *rn)

And the intrinsics:
call void @llvm.aarch64.sme.ldr.zt(i32, ptr)
tail call void @llvm.aarch64.sme.str.zt(i32, ptr)
---
 clang/include/clang/Basic/arm_sme.td  |  5 ++
 clang/include/clang/Basic/arm_sve.td  |  9 
 .../acle_sme2_ldr_str_zt.c| 51 +++
 llvm/include/llvm/IR/IntrinsicsAArch64.td | 11 ++--
 .../Target/AArch64/AArch64ISelDAGToDAG.cpp|  7 ++-
 .../Target/AArch64/AArch64ISelLowering.cpp| 21 
 llvm/lib/Target/AArch64/AArch64ISelLowering.h |  2 +
 .../Target/AArch64/AArch64RegisterInfo.cpp|  6 +++
 .../lib/Target/AArch64/AArch64SMEInstrInfo.td |  4 +-
 llvm/lib/Target/AArch64/SMEInstrFormats.td| 23 +++--
 .../CodeGen/AArch64/sme2-intrinsics-zt0.ll| 27 ++
 11 files changed, 153 insertions(+), 13 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c
 create mode 100644 llvm/test/CodeGen/AArch64/sme2-intrinsics-zt0.ll

diff --git a/clang/include/clang/Basic/arm_sme.td 
b/clang/include/clang/Basic/arm_sme.td
index b5655afdf419ecf..fe3de56ce3298c5 100644
--- a/clang/include/clang/Basic/arm_sme.td
+++ b/clang/include/clang/Basic/arm_sme.td
@@ -298,3 +298,8 @@ multiclass ZAAddSub {
 
 defm SVADD : ZAAddSub<"add">;
 defm SVSUB : ZAAddSub<"sub">;
+
+let TargetGuard = "sme2" in {
+  def SVLDR_ZT : Inst<"svldr_zt", "viQ", "", MergeNone, "aarch64_sme_ldr_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+  def SVSTR_ZT : Inst<"svstr_zt", "vi%", "", MergeNone, "aarch64_sme_str_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+}
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 3d4c2129565903d..f0b3747898d4145 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1813,6 +1813,15 @@ def SVWHILERW_H_BF16 : SInst<"svwhilerw[_{1}]", "Pcc", 
"b", MergeNone, "aarch64_
 def SVWHILEWR_H_BF16 : SInst<"svwhilewr[_{1}]", "Pcc", "b", MergeNone, 
"aarch64_sve_whilewr_h", [IsOverloadWhileRW]>;
 }
 
+// //
+// // Spill and fill of ZT0
+// //
+
+// let TargetGuard = "sme2" in {
+//   def SVLDR_ZT : Inst<"svldr_zt", "viQ", "", "aarch64_sme_ldr_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+//   def SVSTR_ZT : Inst<"svstr_zt", "vi%", "", "aarch64_sme_str_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+// }
+
 

 // SVE2 - Extended table lookup/permute
 let TargetGuard = "sve2" in {
diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c 
b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c
new file mode 100644
index 000..3d70ded6b469ba1
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c
@@ -0,0 +1,51 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+
+// REQUIRES: aarch64-registered-target
+
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - -x c++ %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | 
opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - -x 
c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s 
-check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 -S 
-disable-O0-optnone -Werror -Wall -o /dev/null %s
+
+#include 
+
+#ifdef SVE_OVERLOADED_FORMS
+// A simple used,unused... macro, long enough to represent any SVE builtin.
+#define SVE_ACLE_FUNC(A1,A2_UNUSED) A1
+#else
+#define SVE_ACLE_FUNC(A1,A2) A1##A2
+#endif
+
+// LDR ZT0
+
+// CHECK-LABEL: @test_svldr_zt(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.aarch64.sme.ldr.zt(i32 0, ptr 
[[BASE:%.*]])
+// CHECK-NEXT:ret void
+//
+// CPP-CHECK-LABEL: @_Z13tes

[llvm] [clang] [AArch64][SME2] Add ldr_zt, str_zt builtins and intrinsics (PR #71795)

2023-11-10 Thread Matthew Devereau via cfe-commits

https://github.com/MDevereau updated 
https://github.com/llvm/llvm-project/pull/71795

>From 9846bc9efd79e6e3c2662ea42367c102df88799d Mon Sep 17 00:00:00 2001
From: Matt Devereau 
Date: Thu, 9 Nov 2023 10:50:05 +
Subject: [PATCH 1/4] [AArch64][SME2] Add ldr_zt, str_zt builtins and
 intrinsics

Adds the builtins:

void svldr_zt(uint64_t zt, const void *rn)
void svstr_zt(uint64_t zt, void *rn)

And the intrinsics:
call void @llvm.aarch64.sme.ldr.zt(i32, ptr)
tail call void @llvm.aarch64.sme.str.zt(i32, ptr)
---
 clang/include/clang/Basic/arm_sme.td  |  5 ++
 clang/include/clang/Basic/arm_sve.td  |  9 
 .../acle_sme2_ldr_str_zt.c| 51 +++
 llvm/include/llvm/IR/IntrinsicsAArch64.td | 11 ++--
 .../Target/AArch64/AArch64ISelDAGToDAG.cpp|  7 ++-
 .../Target/AArch64/AArch64ISelLowering.cpp| 21 
 llvm/lib/Target/AArch64/AArch64ISelLowering.h |  2 +
 .../Target/AArch64/AArch64RegisterInfo.cpp|  6 +++
 .../lib/Target/AArch64/AArch64SMEInstrInfo.td |  4 +-
 llvm/lib/Target/AArch64/SMEInstrFormats.td| 23 +++--
 .../CodeGen/AArch64/sme2-intrinsics-zt0.ll| 27 ++
 11 files changed, 153 insertions(+), 13 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c
 create mode 100644 llvm/test/CodeGen/AArch64/sme2-intrinsics-zt0.ll

diff --git a/clang/include/clang/Basic/arm_sme.td 
b/clang/include/clang/Basic/arm_sme.td
index b5655afdf419ecf..fe3de56ce3298c5 100644
--- a/clang/include/clang/Basic/arm_sme.td
+++ b/clang/include/clang/Basic/arm_sme.td
@@ -298,3 +298,8 @@ multiclass ZAAddSub {
 
 defm SVADD : ZAAddSub<"add">;
 defm SVSUB : ZAAddSub<"sub">;
+
+let TargetGuard = "sme2" in {
+  def SVLDR_ZT : Inst<"svldr_zt", "viQ", "", MergeNone, "aarch64_sme_ldr_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+  def SVSTR_ZT : Inst<"svstr_zt", "vi%", "", MergeNone, "aarch64_sme_str_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+}
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 3d4c2129565903d..f0b3747898d4145 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1813,6 +1813,15 @@ def SVWHILERW_H_BF16 : SInst<"svwhilerw[_{1}]", "Pcc", 
"b", MergeNone, "aarch64_
 def SVWHILEWR_H_BF16 : SInst<"svwhilewr[_{1}]", "Pcc", "b", MergeNone, 
"aarch64_sve_whilewr_h", [IsOverloadWhileRW]>;
 }
 
+// //
+// // Spill and fill of ZT0
+// //
+
+// let TargetGuard = "sme2" in {
+//   def SVLDR_ZT : Inst<"svldr_zt", "viQ", "", "aarch64_sme_ldr_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+//   def SVSTR_ZT : Inst<"svstr_zt", "vi%", "", "aarch64_sme_str_zt", 
[IsOverloadNone, IsStreamingCompatible, IsSharedZA, IsPreservesZA], 
[ImmCheck<0, ImmCheck0_0>]>;
+// }
+
 

 // SVE2 - Extended table lookup/permute
 let TargetGuard = "sve2" in {
diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c 
b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c
new file mode 100644
index 000..3d70ded6b469ba1
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_ldr_str_zt.c
@@ -0,0 +1,51 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+
+// REQUIRES: aarch64-registered-target
+
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 -S 
-disable-O0-optnone -Werror -Wall -emit-llvm -o - -x c++ %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - %s | 
opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - -x 
c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s 
-check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 -S 
-disable-O0-optnone -Werror -Wall -o /dev/null %s
+
+#include 
+
+#ifdef SVE_OVERLOADED_FORMS
+// A simple used,unused... macro, long enough to represent any SVE builtin.
+#define SVE_ACLE_FUNC(A1,A2_UNUSED) A1
+#else
+#define SVE_ACLE_FUNC(A1,A2) A1##A2
+#endif
+
+// LDR ZT0
+
+// CHECK-LABEL: @test_svldr_zt(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.aarch64.sme.ldr.zt(i32 0, ptr 
[[BASE:%.*]])
+// CHECK-NEXT:ret void
+//
+// CPP-CHECK-LABEL: @_Z13tes

[llvm] [clang] [AArch64][SME2] Add ldr_zt, str_zt builtins and intrinsics (PR #71795)

2023-11-10 Thread Matthew Devereau via cfe-commits




MDevereau wrote:

Well spotted - I forgot to delete these. Removed

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


  1   2   3   >