[clang] [Clang][Interp] Fix the location of uninitialized base warning (PR #100761)
tbaederr wrote: CC @AaronBallman @Sirraide @shafik Since this adds new API to `CXXBaseSpecifier`. https://github.com/llvm/llvm-project/pull/100761 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5d2c324 - Remove a leftover debug-only statement in CheckExprLifetime.cpp
Author: Haojian Wu Date: 2024-07-29T09:22:03+02:00 New Revision: 5d2c324fea2d7cf86ec50e4bb6b680acf89b2ed5 URL: https://github.com/llvm/llvm-project/commit/5d2c324fea2d7cf86ec50e4bb6b680acf89b2ed5 DIFF: https://github.com/llvm/llvm-project/commit/5d2c324fea2d7cf86ec50e4bb6b680acf89b2ed5.diff LOG: Remove a leftover debug-only statement in CheckExprLifetime.cpp Added: Modified: clang/lib/Sema/CheckExprLifetime.cpp Removed: diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp index 112cf3d081822..7389046eaddde 100644 --- a/clang/lib/Sema/CheckExprLifetime.cpp +++ b/clang/lib/Sema/CheckExprLifetime.cpp @@ -825,7 +825,6 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, if (auto *CCE = dyn_cast(Init)) { if (CCE->getConstructor()->isCopyOrMoveConstructor()) { if (auto *MTE = dyn_cast(CCE->getArg(0))) { -// assert(false && "hit temporary copy path"); Expr *Arg = MTE->getSubExpr(); Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg, CCE->getConstructor()}); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "Reland [clang][ASTImport] Add support for import of empty records" (PR #100903)
https://github.com/balazske approved this pull request. https://github.com/llvm/llvm-project/pull/100903 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Driver] Warn about `-c/-S` with `-fsyntax-only` (PR #98607)
MaskRay wrote: > FWIW, in addition to `-c` in combination with `-fsyntax-only`, this now also > warns for `-c` in combination with `-E`. > > That sounds like a reasonable thing to do to me, so it's probably fine, but > it'd be nice to have that aspect acknowledged as one intended behaviour > change as well. Thanks for pointing this out. Yes, the warning for `-c -E` seems desired. It's a bit difficult to analyze what combinations lead to warnings due to our `claim` code scattering all over the driver https://github.com/llvm/llvm-project/pull/98607 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix misannotations of `<` in ternary expressions (PR #100980)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/100980 Fixes #100300. >From 594a3517f9074cd2794366d3fba5fb4679785ce8 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Mon, 29 Jul 2024 00:19:02 -0700 Subject: [PATCH] [clang-format] Fix misannotations of `<` in ternary expressions Fixes #100300. --- clang/lib/Format/TokenAnnotator.cpp | 42 --- clang/unittests/Format/TokenAnnotatorTest.cpp | 15 +++ 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 16ab18e1af959..800a08bf9d3e7 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -155,8 +155,8 @@ class AnnotatingParser { if (NonTemplateLess.count(CurrentToken->Previous) > 0) return false; -const FormatToken &Previous = *CurrentToken->Previous; // The '<'. -if (Previous.Previous) { +if (const auto &Previous = *CurrentToken->Previous; // The '<'. +Previous.Previous) { if (Previous.Previous->Tok.isLiteral()) return false; if (Previous.Previous->is(tok::r_brace)) @@ -176,11 +176,13 @@ class AnnotatingParser { FormatToken *Left = CurrentToken->Previous; Left->ParentBracket = Contexts.back().ContextKind; ScopedContextCreator ContextCreator(*this, tok::less, 12); - Contexts.back().IsExpression = false; + +const auto *BeforeLess = Left->Previous; + // If there's a template keyword before the opening angle bracket, this is a // template parameter, not an argument. -if (Left->Previous && Left->Previous->isNot(tok::kw_template)) +if (BeforeLess && BeforeLess->isNot(tok::kw_template)) Contexts.back().ContextType = Context::TemplateArgument; if (Style.Language == FormatStyle::LK_Java && @@ -188,19 +190,24 @@ class AnnotatingParser { next(); } -while (CurrentToken) { +for (bool SeenTernaryOperator = false; CurrentToken;) { + const bool InExpr = Contexts[Contexts.size() - 2].IsExpression; if (CurrentToken->is(tok::greater)) { +const auto *Next = CurrentToken->Next; // Try to do a better job at looking for ">>" within the condition of // a statement. Conservatively insert spaces between consecutive ">" // tokens to prevent splitting right bitshift operators and potentially // altering program semantics. This check is overly conservative and // will prevent spaces from being inserted in select nested template // parameter cases, but should not alter program semantics. -if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) && +if (Next && Next->is(tok::greater) && Left->ParentBracket != tok::less && CurrentToken->getStartOfNonWhitespace() == -CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset( --1)) { +Next->getStartOfNonWhitespace().getLocWithOffset(-1)) { + return false; +} +if (InExpr && SeenTernaryOperator && +(!Next || Next->isNot(tok::l_paren))) { return false; } Left->MatchingParen = CurrentToken; @@ -211,14 +218,14 @@ class AnnotatingParser { // msg: < item: data > // In TT_TextProto, map does not occur. if (Style.Language == FormatStyle::LK_TextProto || -(Style.Language == FormatStyle::LK_Proto && Left->Previous && - Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { +(Style.Language == FormatStyle::LK_Proto && BeforeLess && + BeforeLess->isOneOf(TT_SelectorName, TT_DictLiteral))) { CurrentToken->setType(TT_DictLiteral); } else { CurrentToken->setType(TT_TemplateCloser); CurrentToken->Tok.setLength(1); } -if (CurrentToken->Next && CurrentToken->Next->Tok.isLiteral()) +if (Next && Next->Tok.isLiteral()) return false; next(); return true; @@ -230,18 +237,21 @@ class AnnotatingParser { } if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace)) return false; + const auto &Prev = *CurrentToken->Previous; // If a && or || is found and interpreted as a binary operator, this set // of angles is likely part of something like "a < b && c > d". If the // angles are inside an expression, the ||/&& might also be a binary // operator that was misinterpreted because we are parsing template // parameters. // FIXME: This is getting out of hand, write a decent parser. - if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) && - CurrentToken->Previous->is(TT_BinaryOperator) && - Contexts[Contexts.size() - 2].IsExpression && - !Line.startsWith(tok::kw_template)) { -return false; + if (InExpr &&
[clang] [clang-format] Fix misannotations of `<` in ternary expressions (PR #100980)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Fixes #100300. --- Full diff: https://github.com/llvm/llvm-project/pull/100980.diff 2 Files Affected: - (modified) clang/lib/Format/TokenAnnotator.cpp (+26-16) - (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+15) ``diff diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 16ab18e1af959..800a08bf9d3e7 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -155,8 +155,8 @@ class AnnotatingParser { if (NonTemplateLess.count(CurrentToken->Previous) > 0) return false; -const FormatToken &Previous = *CurrentToken->Previous; // The '<'. -if (Previous.Previous) { +if (const auto &Previous = *CurrentToken->Previous; // The '<'. +Previous.Previous) { if (Previous.Previous->Tok.isLiteral()) return false; if (Previous.Previous->is(tok::r_brace)) @@ -176,11 +176,13 @@ class AnnotatingParser { FormatToken *Left = CurrentToken->Previous; Left->ParentBracket = Contexts.back().ContextKind; ScopedContextCreator ContextCreator(*this, tok::less, 12); - Contexts.back().IsExpression = false; + +const auto *BeforeLess = Left->Previous; + // If there's a template keyword before the opening angle bracket, this is a // template parameter, not an argument. -if (Left->Previous && Left->Previous->isNot(tok::kw_template)) +if (BeforeLess && BeforeLess->isNot(tok::kw_template)) Contexts.back().ContextType = Context::TemplateArgument; if (Style.Language == FormatStyle::LK_Java && @@ -188,19 +190,24 @@ class AnnotatingParser { next(); } -while (CurrentToken) { +for (bool SeenTernaryOperator = false; CurrentToken;) { + const bool InExpr = Contexts[Contexts.size() - 2].IsExpression; if (CurrentToken->is(tok::greater)) { +const auto *Next = CurrentToken->Next; // Try to do a better job at looking for ">>" within the condition of // a statement. Conservatively insert spaces between consecutive ">" // tokens to prevent splitting right bitshift operators and potentially // altering program semantics. This check is overly conservative and // will prevent spaces from being inserted in select nested template // parameter cases, but should not alter program semantics. -if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) && +if (Next && Next->is(tok::greater) && Left->ParentBracket != tok::less && CurrentToken->getStartOfNonWhitespace() == -CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset( --1)) { +Next->getStartOfNonWhitespace().getLocWithOffset(-1)) { + return false; +} +if (InExpr && SeenTernaryOperator && +(!Next || Next->isNot(tok::l_paren))) { return false; } Left->MatchingParen = CurrentToken; @@ -211,14 +218,14 @@ class AnnotatingParser { // msg: < item: data > // In TT_TextProto, map does not occur. if (Style.Language == FormatStyle::LK_TextProto || -(Style.Language == FormatStyle::LK_Proto && Left->Previous && - Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { +(Style.Language == FormatStyle::LK_Proto && BeforeLess && + BeforeLess->isOneOf(TT_SelectorName, TT_DictLiteral))) { CurrentToken->setType(TT_DictLiteral); } else { CurrentToken->setType(TT_TemplateCloser); CurrentToken->Tok.setLength(1); } -if (CurrentToken->Next && CurrentToken->Next->Tok.isLiteral()) +if (Next && Next->Tok.isLiteral()) return false; next(); return true; @@ -230,18 +237,21 @@ class AnnotatingParser { } if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace)) return false; + const auto &Prev = *CurrentToken->Previous; // If a && or || is found and interpreted as a binary operator, this set // of angles is likely part of something like "a < b && c > d". If the // angles are inside an expression, the ||/&& might also be a binary // operator that was misinterpreted because we are parsing template // parameters. // FIXME: This is getting out of hand, write a decent parser. - if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) && - CurrentToken->Previous->is(TT_BinaryOperator) && - Contexts[Contexts.size() - 2].IsExpression && - !Line.startsWith(tok::kw_template)) { -return false; + if (InExpr && !Line.startsWith(tok::kw_template) && + Prev.is(TT_BinaryOperator)) { +const auto Precedence = Prev.getPrecedence(); +if (Precedence > prec::Conditio
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
balazske wrote: In the state dump I see that `stdout` seems to be NULL (last line in "constraints"). This explains why the `StateNull` becomes NULL, because call to `assumeNoAliasingWithStdStreams` was called already. I think the better solution is to check NULL-ness of the std stream variable `assumeNoAliasingWithStdStreams` and do not assume if it is NULL. There is not a case when `fopen` returns non-null for sure, but at least not in the current situation, so the current fix is not as good. We could add an `assert` to check if both `StateNull` and `StateNotNull` are non-zero. https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 2db0c00 - [clang][CGDebugInfo] Don't generate an implicit 'this' parameter if one was specified explicitly (#100767)
Author: Michael Buch Date: 2024-07-29T08:47:02+01:00 New Revision: 2db0c00e6092947fa07cc587c4a7537213bbc093 URL: https://github.com/llvm/llvm-project/commit/2db0c00e6092947fa07cc587c4a7537213bbc093 DIFF: https://github.com/llvm/llvm-project/commit/2db0c00e6092947fa07cc587c4a7537213bbc093.diff LOG: [clang][CGDebugInfo] Don't generate an implicit 'this' parameter if one was specified explicitly (#100767) Currently we would unconditionally add an implicit `this` parameter when creating an instance method type. However, when we have an explicit 'this', we shouldn't generate one. This patch only passes a valid `ThisPtr` type to `getOrCreateInstanceMethodType` if one wasn't explicitly specified. There's no way to get a pointer to a member function with an explicit `this` parameter (those are treated as regular function pointers instead). So there's no need to account for that case in `CGDebugInfo::CreateType`. Fixes https://github.com/llvm/llvm-project/issues/99744 Added: clang/test/CodeGenCXX/debug-info-explicit-this.cpp Modified: clang/lib/CodeGen/CGDebugInfo.cpp Removed: diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 3d8a715b692de..b49dee24c3c1a 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -1942,7 +1942,12 @@ CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, if (Method->isStatic()) return cast_or_null( getOrCreateType(QualType(Func, 0), Unit)); - return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit); + + QualType ThisType; + if (!Method->hasCXXExplicitFunctionObjectParameter()) +ThisType = Method->getThisType(); + + return getOrCreateInstanceMethodType(ThisType, Func, Unit); } llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType( @@ -1974,27 +1979,31 @@ llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType( Elts.push_back(Args[0]); // "this" pointer is always first argument. - const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); - if (isa(RD)) { -// Create pointer type directly in this case. -const PointerType *ThisPtrTy = cast(ThisPtr); -uint64_t Size = CGM.getContext().getTypeSize(ThisPtrTy); -auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext()); -llvm::DIType *PointeeType = -getOrCreateType(ThisPtrTy->getPointeeType(), Unit); -llvm::DIType *ThisPtrType = -DBuilder.createPointerType(PointeeType, Size, Align); -TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); -// TODO: This and the artificial type below are misleading, the -// types aren't artificial the argument is, but the current -// metadata doesn't represent that. -ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); -Elts.push_back(ThisPtrType); - } else { -llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit); -TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); -ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); -Elts.push_back(ThisPtrType); + // ThisPtr may be null if the member function has an explicit 'this' + // parameter. + if (!ThisPtr.isNull()) { +const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); +if (isa(RD)) { + // Create pointer type directly in this case. + const PointerType *ThisPtrTy = cast(ThisPtr); + uint64_t Size = CGM.getContext().getTypeSize(ThisPtrTy); + auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext()); + llvm::DIType *PointeeType = + getOrCreateType(ThisPtrTy->getPointeeType(), Unit); + llvm::DIType *ThisPtrType = + DBuilder.createPointerType(PointeeType, Size, Align); + TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); + // TODO: This and the artificial type below are misleading, the + // types aren't artificial the argument is, but the current + // metadata doesn't represent that. + ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); + Elts.push_back(ThisPtrType); +} else { + llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit); + TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); + ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); + Elts.push_back(ThisPtrType); +} } // Copy rest of the arguments. diff --git a/clang/test/CodeGenCXX/debug-info-explicit-this.cpp b/clang/test/CodeGenCXX/debug-info-explicit-this.cpp new file mode 100644 index 0..45ab2a0216ca7 --- /dev/null +++ b/clang/test/CodeGenCXX/debug-info-explicit-this.cpp @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited -std=c++2b %s -o - | FileCheck %s + +struct Foo { + void Bar(this Foo&& self) {} +}; + +void fn() { + Foo{}.Bar(); +} + +// CHECK: distinct !DISubprogram(name: "Bar", {{.*}}, type: ![[BAR_TYPE:[0-9]+]], {
[clang] [clang][CGDebugInfo] Don't generate an implicit 'this' parameter if one was specified explicitly (PR #100767)
https://github.com/Michael137 closed https://github.com/llvm/llvm-project/pull/100767 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 31769e4 - Revert "Reland [clang][ASTImport] Add support for import of empty records" (#100903)
Author: Michael Buch Date: 2024-07-29T08:47:57+01:00 New Revision: 31769e4d0892312948812fbc2d0a56249ea72492 URL: https://github.com/llvm/llvm-project/commit/31769e4d0892312948812fbc2d0a56249ea72492 DIFF: https://github.com/llvm/llvm-project/commit/31769e4d0892312948812fbc2d0a56249ea72492.diff LOG: Revert "Reland [clang][ASTImport] Add support for import of empty records" (#100903) This reverts commit 88e5206f2c96a34e23a4d63f0a38afb2db044f0a. The original change went in a while ago (last year) in https://reviews.llvm.org/D145057. The specific reason I'm proposing a revert is that this is now causing exactly the issue that @balazske predicted in https://reviews.llvm.org/D145057#4164717: > Problematic case is if the attribute has pointer to a Decl or Type that is imported here in a state when the field is already created but not initialized. Another problem is that attributes are added a second time in Import(Decl *) This now came up in the testing of LLDB support for https://github.com/llvm/llvm-project/issues/93069. There, `__compressed_pair`s are now replaced with fields that have an `alignof(...)` and `[[no_unique_address]]` attribute. In the specific failing case, we're importing following `std::list` method: ``` size_type& __sz() _NOEXCEPT { return __size_; } ``` During this process, we create a new `__size_` `FieldDecl` (but don't initialize it yet). Then we go down the `ImportAttrs` codepath added in D145057. This imports the `alignof` expression which then references the uninitialized `__size_` and we trigger an assertion. Important to note, this codepath was added specifically to support `[[no_unique_address]]` in LLDB, and was supposed to land with https://reviews.llvm.org/D143347. But the LLDB side of that never landed, and the way we plan to support `[[no_unique_address]]` doesn't require things like the `markEmpty` method added here. So really, this is a dead codepath, which as pointed out in the original review isn't fully sound. Added: Modified: clang/include/clang/AST/ASTImporter.h clang/include/clang/AST/DeclCXX.h clang/lib/AST/ASTImporter.cpp clang/unittests/AST/ASTImporterTest.cpp Removed: diff --git a/clang/include/clang/AST/ASTImporter.h b/clang/include/clang/AST/ASTImporter.h index 4ffd913846575..f851decd0965c 100644 --- a/clang/include/clang/AST/ASTImporter.h +++ b/clang/include/clang/AST/ASTImporter.h @@ -258,7 +258,6 @@ class TypeSourceInfo; FoundDeclsTy findDeclsInToCtx(DeclContext *DC, DeclarationName Name); void AddToLookupTable(Decl *ToD); -llvm::Error ImportAttrs(Decl *ToD, Decl *FromD); protected: /// Can be overwritten by subclasses to implement their own import logic. diff --git a/clang/include/clang/AST/DeclCXX.h b/clang/include/clang/AST/DeclCXX.h index fb52ac804849d..3a110454f29ed 100644 --- a/clang/include/clang/AST/DeclCXX.h +++ b/clang/include/clang/AST/DeclCXX.h @@ -1188,10 +1188,6 @@ class CXXRecordDecl : public RecordDecl { /// /// \note This does NOT include a check for union-ness. bool isEmpty() const { return data().Empty; } - /// Marks this record as empty. This is used by DWARFASTParserClang - /// when parsing records with empty fields having [[no_unique_address]] - /// attribute - void markEmpty() { data().Empty = true; } void setInitMethod(bool Val) { data().HasInitMethod = Val; } bool hasInitMethod() const { return data().HasInitMethod; } diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp index 08ef09d353afc..da1981d8dd05f 100644 --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -4179,12 +4179,6 @@ ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { D->getInClassInitStyle())) return ToField; - // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before - // we add fields in CXXRecordDecl::addedMember, otherwise record will be - // marked as having non-zero size. - Err = Importer.ImportAttrs(ToField, D); - if (Err) -return std::move(Err); ToField->setAccess(D->getAccess()); ToField->setLexicalDeclContext(LexicalDC); ToField->setImplicit(D->isImplicit()); @@ -9399,19 +9393,6 @@ TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) { return FromDPos->second->getTranslationUnitDecl(); } -Error ASTImporter::ImportAttrs(Decl *ToD, Decl *FromD) { - if (!FromD->hasAttrs() || ToD->hasAttrs()) -return Error::success(); - for (const Attr *FromAttr : FromD->getAttrs()) { -auto ToAttrOrErr = Import(FromAttr); -if (ToAttrOrErr) - ToD->addAttr(*ToAttrOrErr); -else - return ToAttrOrErr.takeError(); - } - return Error::success(); -} - Expected ASTImporter::Import(Decl *FromD) { if (!FromD) return nullptr; @@ -9545,8 +9526,15 @@ Expected ASTImporter::Import(Decl *FromD) { } // Make sure that ImportImpl registered the impo
[clang] Revert "Reland [clang][ASTImport] Add support for import of empty records" (PR #100903)
https://github.com/Michael137 closed https://github.com/llvm/llvm-project/pull/100903 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)
DominikAdamski wrote: @jhuber6 You are right. Flang-new for AMD GPU requires `-mlink-builtin-bitcode` for math functions. https://github.com/llvm/llvm-project/pull/96742 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)
https://github.com/DominikAdamski updated https://github.com/llvm/llvm-project/pull/96742 >From 5b487aac3c8414b6f37f6888f361ca7488094048 Mon Sep 17 00:00:00 2001 From: Dominik Adamski Date: Fri, 21 Jun 2024 18:03:53 +0200 Subject: [PATCH 1/5] [Flang-new][OpenMP] Add offload related flags for AMDGPU Flang-new needs to add mlink-builtin-bitcode objects to properly support offload code generation for AMD GPU. fcuda-is-device flag is not used by Flang currently. In the future it will be needed for Flang equivalent function: AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace. --- clang/include/clang/Driver/Options.td | 4 +- clang/lib/Driver/ToolChains/Flang.cpp | 3 ++ flang/test/Driver/omp-driver-offload.f90 | 58 +-- flang/test/Driver/target-cpu-features.f90 | 4 +- flang/test/Driver/target-gpu-features.f90 | 2 +- 5 files changed, 41 insertions(+), 30 deletions(-) diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index dd55838dcf384..612d5793232ce 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -8016,7 +8016,7 @@ def source_date_epoch : Separate<["-"], "source-date-epoch">, // CUDA Options //===--===// -let Visibility = [CC1Option] in { +let Visibility = [CC1Option, FC1Option] in { def fcuda_is_device : Flag<["-"], "fcuda-is-device">, HelpText<"Generate code for CUDA device">, @@ -8031,7 +8031,7 @@ def fno_cuda_host_device_constexpr : Flag<["-"], "fno-cuda-host-device-constexpr HelpText<"Don't treat unattributed constexpr functions as __host__ __device__.">, MarshallingInfoNegativeFlag>; -} // let Visibility = [CC1Option] +} // let Visibility = [CC1Option, FC1Option] //===--===// // OpenMP Options diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp index 42b45dba2bd31..2679f284c5016 100644 --- a/clang/lib/Driver/ToolChains/Flang.cpp +++ b/clang/lib/Driver/ToolChains/Flang.cpp @@ -333,6 +333,9 @@ void Flang::AddAMDGPUTargetArgs(const ArgList &Args, StringRef Val = A->getValue(); CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val)); } + + const ToolChain &TC = getToolChain(); + TC.addClangTargetOptions(Args, CmdArgs, Action::OffloadKind::OFK_OpenMP); } void Flang::addTargetOptions(const ArgList &Args, diff --git a/flang/test/Driver/omp-driver-offload.f90 b/flang/test/Driver/omp-driver-offload.f90 index 6fb4f4ca1..da81a6ee3ba8f 100644 --- a/flang/test/Driver/omp-driver-offload.f90 +++ b/flang/test/Driver/omp-driver-offload.f90 @@ -14,12 +14,12 @@ ! Test regular -fopenmp with offload, and invocation filtering options ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-HOST-AND-DEVICE ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 --offload-host-device \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-HOST-AND-DEVICE ! OFFLOAD-HOST-AND-DEVICE: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" @@ -29,7 +29,7 @@ ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 --offload-host-only \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-HOST ! OFFLOAD-HOST: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" @@ -39,7 +39,7 @@ ! RUN: %flang -S -### %s 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 --offload-device-only \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-DEVICE ! OFFLOAD-DEVICE: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" @@ -48,13 +48,13 @@ ! OFFLOAD-DEVICE-NOT: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" ! Test regular -fopenmp with offload for basic fopenmp-is-target-device flag addition and correct fopenmp -! RUN: %flang -### -fopenmp --offload-arch=gfx90a -fopenmp-targets=amdgcn-amd-amdhsa %s 2>&1 | FileCheck --check-prefixes=CHECK-OPENMP-IS-TARGET-DEVICE %s +! RUN: %flang -### -fopenmp --offload-arch=gfx90a -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib %s 2>&1 | FileCheck --check-prefixes=CHECK-OPENMP-IS-TARGET-DEVICE %s ! CHECK-OPENMP-IS-TARGET-DEVICE: "{{[^"]*}}flang-new" "-fc1" {{.*}} "-fopenmp" {{.*}} "-fopenmp-is-target-device" {{.*}}.f90" ! Testing appropriate flags are gnerated and appropriately assigned by the dr
[clang] [clang][CodeGen] Don't crash on output whose size is zero. (PR #99849)
https://github.com/yetingk updated https://github.com/llvm/llvm-project/pull/99849 >From 86221475bc98c0115cad564b1dc36a96544e921d Mon Sep 17 00:00:00 2001 From: Yeting Kuo Date: Mon, 22 Jul 2024 01:18:51 -0700 Subject: [PATCH] [clang][CodeGen] Don't crash on output whose size is zero. This fixes issue #63878 caused by creating an integer with zero bitwidth. --- clang/lib/CodeGen/CGStmt.cpp | 5 - clang/test/CodeGen/inline-asm-size-zero.c | 6 ++ 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 clang/test/CodeGen/inline-asm-size-zero.c diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp index aa97f685ac7a9..e16aa3cdd5506 100644 --- a/clang/lib/CodeGen/CGStmt.cpp +++ b/clang/lib/CodeGen/CGStmt.cpp @@ -2751,7 +2751,10 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { if (RequiresCast) { unsigned Size = getContext().getTypeSize(QTy); -Ty = llvm::IntegerType::get(getLLVMContext(), Size); +if (Size) + Ty = llvm::IntegerType::get(getLLVMContext(), Size); +else + CGM.Error(OutExpr->getExprLoc(), "output size should not be zero"); } ResultRegTypes.push_back(Ty); // If this output is tied to an input, and if the input is larger, then diff --git a/clang/test/CodeGen/inline-asm-size-zero.c b/clang/test/CodeGen/inline-asm-size-zero.c new file mode 100644 index 0..564f5207d1e71 --- /dev/null +++ b/clang/test/CodeGen/inline-asm-size-zero.c @@ -0,0 +1,6 @@ +// RUN: not %clang_cc1 -S %s -verify -o - + +void foo(void) { +extern long bar[]; +asm ("" : "=r"(bar)); // expected-error{{output size should not be zero}} +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CodeGen] Don't crash on output whose size is zero. (PR #99849)
yetingk wrote: Rebase and ping. https://github.com/llvm/llvm-project/pull/99849 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
steakhal wrote: > In the state dump I see that `stdout` seems to be NULL (last line in > "constraints"). This explains why the `StateNull` becomes NULL, because call > to `assumeNoAliasingWithStdStreams` was called already. I think the better > solution is to check NULL-ness of the std stream variable > `assumeNoAliasingWithStdStreams` and do not assume if it is NULL. There is > not a case when `fopen` returns non-null for sure, but at least not in the > current situation, so the current fix is not as good. We could add an > `assert` to check if both `StateNull` and `StateNotNull` are non-zero. Exactly. I didn't want to rush too much, but I can share that my current idea is to call `assumeNoAliasingWithStdStreams` only on the success path. https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [RISCV] full support for riscv_rvv_vector_bits attribute (PR #100110)
vbe-sc wrote: @topperc, could you please have a look at this patch https://github.com/llvm/llvm-project/pull/100110 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
balazske wrote: > Exactly. I didn't want to rush too much, but I can share that my current idea > is to call `assumeNoAliasingWithStdStreams` only on the success path. This can be a better (and more simple) solution. https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver] Have getTargetSubDirPath better match get_compiler_rt_target (PR #100091)
https://github.com/rorth milestoned https://github.com/llvm/llvm-project/pull/100091 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
https://github.com/ivanaivanovska created https://github.com/llvm/llvm-project/pull/100985 When a plain return statement was used in a coroutine, the error "return statement not allowed in coroutine" was surfaced too late (e.g. after other errors in the return statement). Surfacing it earlier now, to make the issue more obvious. >From 8ee4d7bcdbc186e86d4ff2374b12a54f05d1fc38 Mon Sep 17 00:00:00 2001 From: Ivana Ivanovska Date: Mon, 29 Jul 2024 08:08:00 + Subject: [PATCH] Surface error for plain return statement in coroutine earlier --- clang/lib/Sema/SemaCoroutine.cpp | 2 +- clang/lib/Sema/SemaStmt.cpp | 10 + clang/test/SemaCXX/coroutines.cpp | 35 +++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp index 81334c817b2af..87d0d44c5af66 100644 --- a/clang/lib/Sema/SemaCoroutine.cpp +++ b/clang/lib/Sema/SemaCoroutine.cpp @@ -1120,7 +1120,7 @@ void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { // [stmt.return.coroutine]p1: // A coroutine shall not enclose a return statement ([stmt.return]). - if (Fn->FirstReturnLoc.isValid()) { + if (Fn->FirstReturnLoc.isValid() && Fn->FirstReturnLoc < Fn->FirstCoroutineStmtLoc) { assert(Fn->FirstCoroutineStmtLoc.isValid() && "first coroutine location not set"); Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp index 34d2d398f244d..3909892ef0a6f 100644 --- a/clang/lib/Sema/SemaStmt.cpp +++ b/clang/lib/Sema/SemaStmt.cpp @@ -3747,6 +3747,16 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct) << /*return*/ 1 << /*out of */ 0); + // using plain return in a coroutine is not allowed. + FunctionScopeInfo *FSI = getCurFunction(); + if (getLangOpts().Coroutines && FSI->isCoroutine()) { +assert(FSI->FirstCoroutineStmtLoc.isValid() && + "first coroutine location not set"); +Diag(ReturnLoc, diag::err_return_in_coroutine); +Diag(FSI->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) +<< FSI->getFirstCoroutineStmtKeyword(); + } + StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true); if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext()) diff --git a/clang/test/SemaCXX/coroutines.cpp b/clang/test/SemaCXX/coroutines.cpp index 2292932583fff..b4f362c621929 100644 --- a/clang/test/SemaCXX/coroutines.cpp +++ b/clang/test/SemaCXX/coroutines.cpp @@ -154,12 +154,15 @@ namespace std { template struct coroutine_handle { static coroutine_handle from_address(void *) noexcept; + static coroutine_handle from_promise(PromiseType &promise); }; template <> struct coroutine_handle { template coroutine_handle(coroutine_handle) noexcept; static coroutine_handle from_address(void *) noexcept; + template + static coroutine_handle from_promise(PromiseType &promise); }; } // namespace std @@ -291,6 +294,38 @@ void mixed_coreturn_template2(bool b, T) { return; // expected-error {{not allowed in coroutine}} } +struct promise_handle; + +struct Handle : std::coroutine_handle { // expected-note 2{{candidate constructor (the implicit copy constructor) not viable}} +// expected-note@-1 2{{candidate constructor (the implicit move constructor) not viable}} +using promise_type = promise_handle; +}; + +struct promise_handle { +Handle get_return_object() noexcept { + { return Handle(std::coroutine_handle::from_promise(*this)); } +} +suspend_never initial_suspend() const noexcept { return {}; } +suspend_never final_suspend() const noexcept { return {}; } +void return_void() const noexcept {} +void unhandled_exception() const noexcept {} +}; + +Handle mixed_return_value() { + co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} + return 0; // expected-error {{return statement not allowed in coroutine}} + // expected-error@-1 {{no viable conversion from returned value of type}} +} + +Handle mixed_return_value_return_first(bool b) { + if (b) { +return 0; // expected-error {{no viable conversion from returned value of type}} +// expected-error@-1 {{return statement not allowed in coroutine}} +} +co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} +co_return 0; // expected-error {{no member named 'return_value' in 'promise_handle'}} +} + struct CtorDtor { CtorDtor() { co_yield 0; // expected-error {{'co_yield' cannot be used in a constructor}} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (ivanaivanovska) Changes When a plain return statement was used in a coroutine, the error "return statement not allowed in coroutine" was surfaced too late (e.g. after other errors in the return statement). Surfacing it earlier now, to make the issue more obvious. --- Full diff: https://github.com/llvm/llvm-project/pull/100985.diff 3 Files Affected: - (modified) clang/lib/Sema/SemaCoroutine.cpp (+1-1) - (modified) clang/lib/Sema/SemaStmt.cpp (+10) - (modified) clang/test/SemaCXX/coroutines.cpp (+35) ``diff diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp index 81334c817b2af..87d0d44c5af66 100644 --- a/clang/lib/Sema/SemaCoroutine.cpp +++ b/clang/lib/Sema/SemaCoroutine.cpp @@ -1120,7 +1120,7 @@ void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { // [stmt.return.coroutine]p1: // A coroutine shall not enclose a return statement ([stmt.return]). - if (Fn->FirstReturnLoc.isValid()) { + if (Fn->FirstReturnLoc.isValid() && Fn->FirstReturnLoc < Fn->FirstCoroutineStmtLoc) { assert(Fn->FirstCoroutineStmtLoc.isValid() && "first coroutine location not set"); Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp index 34d2d398f244d..3909892ef0a6f 100644 --- a/clang/lib/Sema/SemaStmt.cpp +++ b/clang/lib/Sema/SemaStmt.cpp @@ -3747,6 +3747,16 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct) << /*return*/ 1 << /*out of */ 0); + // using plain return in a coroutine is not allowed. + FunctionScopeInfo *FSI = getCurFunction(); + if (getLangOpts().Coroutines && FSI->isCoroutine()) { +assert(FSI->FirstCoroutineStmtLoc.isValid() && + "first coroutine location not set"); +Diag(ReturnLoc, diag::err_return_in_coroutine); +Diag(FSI->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) +<< FSI->getFirstCoroutineStmtKeyword(); + } + StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true); if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext()) diff --git a/clang/test/SemaCXX/coroutines.cpp b/clang/test/SemaCXX/coroutines.cpp index 2292932583fff..b4f362c621929 100644 --- a/clang/test/SemaCXX/coroutines.cpp +++ b/clang/test/SemaCXX/coroutines.cpp @@ -154,12 +154,15 @@ namespace std { template struct coroutine_handle { static coroutine_handle from_address(void *) noexcept; + static coroutine_handle from_promise(PromiseType &promise); }; template <> struct coroutine_handle { template coroutine_handle(coroutine_handle) noexcept; static coroutine_handle from_address(void *) noexcept; + template + static coroutine_handle from_promise(PromiseType &promise); }; } // namespace std @@ -291,6 +294,38 @@ void mixed_coreturn_template2(bool b, T) { return; // expected-error {{not allowed in coroutine}} } +struct promise_handle; + +struct Handle : std::coroutine_handle { // expected-note 2{{candidate constructor (the implicit copy constructor) not viable}} +// expected-note@-1 2{{candidate constructor (the implicit move constructor) not viable}} +using promise_type = promise_handle; +}; + +struct promise_handle { +Handle get_return_object() noexcept { + { return Handle(std::coroutine_handle::from_promise(*this)); } +} +suspend_never initial_suspend() const noexcept { return {}; } +suspend_never final_suspend() const noexcept { return {}; } +void return_void() const noexcept {} +void unhandled_exception() const noexcept {} +}; + +Handle mixed_return_value() { + co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} + return 0; // expected-error {{return statement not allowed in coroutine}} + // expected-error@-1 {{no viable conversion from returned value of type}} +} + +Handle mixed_return_value_return_first(bool b) { + if (b) { +return 0; // expected-error {{no viable conversion from returned value of type}} +// expected-error@-1 {{return statement not allowed in coroutine}} +} +co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} +co_return 0; // expected-error {{no member named 'return_value' in 'promise_handle'}} +} + struct CtorDtor { CtorDtor() { co_yield 0; // expected-error {{'co_yield' cannot be used in a constructor}} `` https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
llvmbot wrote: @llvm/pr-subscribers-coroutines Author: None (ivanaivanovska) Changes When a plain return statement was used in a coroutine, the error "return statement not allowed in coroutine" was surfaced too late (e.g. after other errors in the return statement). Surfacing it earlier now, to make the issue more obvious. --- Full diff: https://github.com/llvm/llvm-project/pull/100985.diff 3 Files Affected: - (modified) clang/lib/Sema/SemaCoroutine.cpp (+1-1) - (modified) clang/lib/Sema/SemaStmt.cpp (+10) - (modified) clang/test/SemaCXX/coroutines.cpp (+35) ``diff diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp index 81334c817b2af..87d0d44c5af66 100644 --- a/clang/lib/Sema/SemaCoroutine.cpp +++ b/clang/lib/Sema/SemaCoroutine.cpp @@ -1120,7 +1120,7 @@ void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { // [stmt.return.coroutine]p1: // A coroutine shall not enclose a return statement ([stmt.return]). - if (Fn->FirstReturnLoc.isValid()) { + if (Fn->FirstReturnLoc.isValid() && Fn->FirstReturnLoc < Fn->FirstCoroutineStmtLoc) { assert(Fn->FirstCoroutineStmtLoc.isValid() && "first coroutine location not set"); Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp index 34d2d398f244d..3909892ef0a6f 100644 --- a/clang/lib/Sema/SemaStmt.cpp +++ b/clang/lib/Sema/SemaStmt.cpp @@ -3747,6 +3747,16 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct) << /*return*/ 1 << /*out of */ 0); + // using plain return in a coroutine is not allowed. + FunctionScopeInfo *FSI = getCurFunction(); + if (getLangOpts().Coroutines && FSI->isCoroutine()) { +assert(FSI->FirstCoroutineStmtLoc.isValid() && + "first coroutine location not set"); +Diag(ReturnLoc, diag::err_return_in_coroutine); +Diag(FSI->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) +<< FSI->getFirstCoroutineStmtKeyword(); + } + StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true); if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext()) diff --git a/clang/test/SemaCXX/coroutines.cpp b/clang/test/SemaCXX/coroutines.cpp index 2292932583fff..b4f362c621929 100644 --- a/clang/test/SemaCXX/coroutines.cpp +++ b/clang/test/SemaCXX/coroutines.cpp @@ -154,12 +154,15 @@ namespace std { template struct coroutine_handle { static coroutine_handle from_address(void *) noexcept; + static coroutine_handle from_promise(PromiseType &promise); }; template <> struct coroutine_handle { template coroutine_handle(coroutine_handle) noexcept; static coroutine_handle from_address(void *) noexcept; + template + static coroutine_handle from_promise(PromiseType &promise); }; } // namespace std @@ -291,6 +294,38 @@ void mixed_coreturn_template2(bool b, T) { return; // expected-error {{not allowed in coroutine}} } +struct promise_handle; + +struct Handle : std::coroutine_handle { // expected-note 2{{candidate constructor (the implicit copy constructor) not viable}} +// expected-note@-1 2{{candidate constructor (the implicit move constructor) not viable}} +using promise_type = promise_handle; +}; + +struct promise_handle { +Handle get_return_object() noexcept { + { return Handle(std::coroutine_handle::from_promise(*this)); } +} +suspend_never initial_suspend() const noexcept { return {}; } +suspend_never final_suspend() const noexcept { return {}; } +void return_void() const noexcept {} +void unhandled_exception() const noexcept {} +}; + +Handle mixed_return_value() { + co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} + return 0; // expected-error {{return statement not allowed in coroutine}} + // expected-error@-1 {{no viable conversion from returned value of type}} +} + +Handle mixed_return_value_return_first(bool b) { + if (b) { +return 0; // expected-error {{no viable conversion from returned value of type}} +// expected-error@-1 {{return statement not allowed in coroutine}} +} +co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} +co_return 0; // expected-error {{no member named 'return_value' in 'promise_handle'}} +} + struct CtorDtor { CtorDtor() { co_yield 0; // expected-error {{'co_yield' cannot be used in a constructor}} `` https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Demote always_inline error to warning for mismatching SME attrs (PR #100740)
https://github.com/sdesmalen-arm milestoned https://github.com/llvm/llvm-project/pull/100740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5430f73 - [Clang] Demote always_inline error to warning for mismatching SME attrs (#100740)
Author: Sander de Smalen Date: 2024-07-29T09:29:30+01:00 New Revision: 5430f73b501f9fc0a38c3768592f5f31bcbdf2f0 URL: https://github.com/llvm/llvm-project/commit/5430f73b501f9fc0a38c3768592f5f31bcbdf2f0 DIFF: https://github.com/llvm/llvm-project/commit/5430f73b501f9fc0a38c3768592f5f31bcbdf2f0.diff LOG: [Clang] Demote always_inline error to warning for mismatching SME attrs (#100740) PR #77936 introduced a diagnostic to avoid calls being inlined into functions with a different streaming mode, because inlining those functions may result in different runtime behaviour. This was necessary because LLVM doesn't check whether inlining is possible and thus blindly inlines the function without checking feasibility. In practice however, this introduces an artificial restriction that the user may not be able to work around. Calling an `always_inline` function from some header file that is out of the control of the user would result in an error that the user cannot remedy. Therefore, this patch demotes the error into a warning (for calls from streaming[-compatible] -> non-streaming), but the proper fix would be to fix the AlwaysInliner in LLVM to avoid inlining when it has analyzed the callee and has determined that inlining is not possible. Calling an always_inline function for calls from non-streaming -> streaming will remain an error, because there is little pre-existing code for SME, so it is expected that the header file can be modified by the user (e.g. by using `__arm_streaming_compatible` if the code is claimed to be compatible). Added: Modified: clang/include/clang/Basic/DiagnosticFrontendKinds.td clang/lib/CodeGen/Targets/AArch64.cpp clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c Removed: diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 12a4617c64d87..8a1462c670d68 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,6 +288,9 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; +def warn_function_always_inline_attribute_mismatch : Warning< + "always_inline function %1 and its caller %0 have mismatching %2 attributes, " + "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index b9df54b0c67c4..1dec3cd40ebd2 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,8 +883,10 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report(CallLoc, - diag::err_function_always_inline_attribute_mismatch) +CGM.getDiags().Report( +CallLoc, CalleeIsStreaming + ? diag::err_function_always_inline_attribute_mismatch + : diag::warn_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 25aebeced9379..98370a888ac6c 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -20,7 +20,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +29,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching
[clang] [Clang] Demote always_inline error to warning for mismatching SME attrs (PR #100740)
https://github.com/sdesmalen-arm closed https://github.com/llvm/llvm-project/pull/100740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Keep alive short-circuiting condition subexpressions in a conditional (PR #100745)
https://github.com/Xazax-hun commented: Nice catch, thanks for fixing! https://github.com/llvm/llvm-project/pull/100745 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Demote always_inline error to warning for mismatching SME attrs (PR #100740)
sdesmalen-arm wrote: /cherry-pick 5430f73b501f9fc0a38c3768592f5f31bcbdf2f0 https://github.com/llvm/llvm-project/pull/100740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][dataflow] Fix bug in `buildContainsExprConsumedInDifferentBlock()`. (PR #100874)
https://github.com/Xazax-hun approved this pull request. LGTM! https://github.com/llvm/llvm-project/pull/100874 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Demote always_inline error to warning for mismatching SME attrs (PR #100740)
llvmbot wrote: /pull-request llvm/llvm-project#100987 https://github.com/llvm/llvm-project/pull/100740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)
https://github.com/DominikAdamski edited https://github.com/llvm/llvm-project/pull/96742 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][FMV][AArch64] Improve streaming mode compatibility. (PR #100181)
labrinea wrote: /cherry-pick [f8ae128](https://github.com/llvm/llvm-project/commit/f8ae128755777424cf4133e4e8e819c0bc08d2b1) https://github.com/llvm/llvm-project/pull/100181 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Use double hyphen for multiple-letter flags (PR #100978)
https://github.com/magic-akari ready_for_review https://github.com/llvm/llvm-project/pull/100978 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Use double hyphen for multiple-letter flags (PR #100978)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: None (magic-akari) Changes - Closes: #100974 --- Full diff: https://github.com/llvm/llvm-project/pull/100978.diff 5 Files Affected: - (modified) clang/tools/clang-format/clang-format-diff.py (+4-4) - (modified) clang/tools/clang-format/clang-format-sublime.py (+4-4) - (modified) clang/tools/clang-format/clang-format.el (+7-7) - (modified) clang/tools/clang-format/clang-format.py (+8-8) - (modified) clang/tools/clang-format/git-clang-format (+3-3) ``diff diff --git a/clang/tools/clang-format/clang-format-diff.py b/clang/tools/clang-format/clang-format-diff.py index 3a74b90e73157..9eec0f3c89de3 100755 --- a/clang/tools/clang-format/clang-format-diff.py +++ b/clang/tools/clang-format/clang-format-diff.py @@ -134,7 +134,7 @@ def main(): if line_count != 0: end_line += line_count - 1 lines_by_file.setdefault(filename, []).extend( -["-lines", str(start_line) + ":" + str(end_line)] +["--lines", str(start_line) + ":" + str(end_line)] ) # Reformat files containing changes in place. @@ -146,12 +146,12 @@ def main(): if args.i: command.append("-i") if args.sort_includes: -command.append("-sort-includes") +command.append("--sort-includes") command.extend(lines) if args.style: -command.extend(["-style", args.style]) +command.extend(["--style", args.style]) if args.fallback_style: -command.extend(["-fallback-style", args.fallback_style]) +command.extend(["--fallback-style", args.fallback_style]) try: p = subprocess.Popen( diff --git a/clang/tools/clang-format/clang-format-sublime.py b/clang/tools/clang-format/clang-format-sublime.py index dcd72e68e94fa..8d41da332c188 100644 --- a/clang/tools/clang-format/clang-format-sublime.py +++ b/clang/tools/clang-format/clang-format-sublime.py @@ -35,18 +35,18 @@ def run(self, edit): regions = [] command = [binary] if style: -command.extend(["-style", style]) +command.extend(["--style", style]) for region in self.view.sel(): regions.append(region) region_offset = min(region.a, region.b) region_length = abs(region.b - region.a) command.extend( [ -"-offset", +"--offset", str(region_offset), -"-length", +"--length", str(region_length), -"-assume-filename", +"--assume-filename", str(self.view.file_name()), ] ) diff --git a/clang/tools/clang-format/clang-format.el b/clang/tools/clang-format/clang-format.el index f43bf063c6297..f3da5415f8672 100644 --- a/clang/tools/clang-format/clang-format.el +++ b/clang/tools/clang-format/clang-format.el @@ -166,19 +166,19 @@ uses the function `buffer-file-name'." (let ((status (apply #'call-process-region nil nil clang-format-executable nil `(,temp-buffer ,temp-file) nil - `("-output-replacements-xml" + `("--output-replacements-xml" ;; Guard against a nil assume-file-name. ;; If the clang-format option -assume-filename ;; is given a blank string it will crash as per ;; the following bug report ;; https://bugs.llvm.org/show_bug.cgi?id=34667 ,@(and assume-file-name - (list "-assume-filename" assume-file-name)) - ,@(and style (list "-style" style)) - "-fallback-style" ,clang-format-fallback-style - "-offset" ,(number-to-string file-start) - "-length" ,(number-to-string (- file-end file-start)) - "-cursor" ,(number-to-string cursor + (list "--assume-filename" assume-file-name)) + ,@(and style (list "--style" style)) + "--fallback-style" ,clang-format-fallback-style + "--offset" ,(number-to-string file-start) + "--length" ,(number-to-string (- file-end file-start)) + "--cursor" ,(number-to-string cursor (stderr (with-temp-buffer (unless (zerop (cadr (insert-file-contents temp-file))) (insert ": ")) diff --git a/clang/tools/clang-form
[clang] [clang][FMV][AArch64] Improve streaming mode compatibility. (PR #100181)
llvmbot wrote: Failed to cherry-pick: [f8ae128](https://github.com/llvm/llvm-project/commit/f8ae128755777424cf4133e4e8e819c0bc08d2b1) https://github.com/llvm/llvm-project/actions/runs/10140964466 Please manually backport the fix and push it to your github fork. Once this is done, please create a [pull request](https://github.com/llvm/llvm-project/compare) https://github.com/llvm/llvm-project/pull/100181 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][ASTImporter] Fix import of template parameter default values. (PR #100100)
https://github.com/balazske updated https://github.com/llvm/llvm-project/pull/100100 From e4440b82f3d1fe5c7cafbad87da0e266d35a619e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= Date: Tue, 23 Jul 2024 11:20:22 +0200 Subject: [PATCH 1/2] [clang][ASTImporter] Fix import of template parameter default values. Default values of template parameters (non-type, type, template) were not correctly handled in the "inherited" case. This occurs if the first declaration contains the default value but a next one not. The default value is "inherited" from the first. In ASTImporter it was only possible to set the inherited status after the template object was created with the template parameters that were imported without handling the inherited case. The import function of the template parameter contains not enough information (previous declaration) to set the inherited-from status. After the template was created, default value of the parameters that should be inherited is reset to inherited mode. --- clang/lib/AST/ASTImporter.cpp | 34 +++ clang/unittests/AST/ASTImporterTest.cpp | 125 2 files changed, 159 insertions(+) diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp index 08ef09d353afc..1d9ea714780ce 100644 --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -359,6 +359,31 @@ namespace clang { Params, Importer.getToContext().getTranslationUnitDecl()); } +template +void tryUpdateTemplateParmDeclInheritedFrom(NamedDecl *RecentParm, +NamedDecl *NewParm) { + if (auto *ParmT = dyn_cast(RecentParm)) { +if (ParmT->hasDefaultArgument()) { + auto *P = cast(NewParm); + P->removeDefaultArgument(); + P->setInheritedDefaultArgument(Importer.ToContext, ParmT); +} + } +} + +void updateTemplateParametersInheritedFrom( +const TemplateParameterList &RecentParams, +TemplateParameterList &NewParams) { + for (auto [Idx, Param] : enumerate(RecentParams)) { +tryUpdateTemplateParmDeclInheritedFrom( +Param, NewParams.getParam(Idx)); +tryUpdateTemplateParmDeclInheritedFrom( +Param, NewParams.getParam(Idx)); +tryUpdateTemplateParmDeclInheritedFrom( +Param, NewParams.getParam(Idx)); + } +} + public: explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} @@ -6138,6 +6163,9 @@ ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { } D2->setPreviousDecl(Recent); + +updateTemplateParametersInheritedFrom(*(Recent->getTemplateParameters()), + **TemplateParamsOrErr); } return D2; @@ -6452,6 +6480,9 @@ ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { ToTemplated->setPreviousDecl(PrevTemplated); } ToVarTD->setPreviousDecl(Recent); + +updateTemplateParametersInheritedFrom(*(Recent->getTemplateParameters()), + **TemplateParamsOrErr); } return ToVarTD; @@ -6724,6 +6755,9 @@ ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { TemplatedFD->setPreviousDecl(PrevTemplated); } ToFunc->setPreviousDecl(Recent); + +updateTemplateParametersInheritedFrom(*(Recent->getTemplateParameters()), + *Params); } return ToFunc; diff --git a/clang/unittests/AST/ASTImporterTest.cpp b/clang/unittests/AST/ASTImporterTest.cpp index 6d987cc7e9ec6..ed64593ae2f0b 100644 --- a/clang/unittests/AST/ASTImporterTest.cpp +++ b/clang/unittests/AST/ASTImporterTest.cpp @@ -9783,6 +9783,128 @@ TEST_P(ASTImporterOptionSpecificTestBase, ImportExistingEmptyAnonymousEnums) { EXPECT_EQ(ImportedE2, ToE1); } +struct ImportTemplateParmDeclDefaultValue +: public ASTImporterOptionSpecificTestBase { +protected: + void checkTemplateParams(RedeclarableTemplateDecl *D) { +auto *CanD = cast(D->getCanonicalDecl()); +auto *CanNonTypeP = cast( +CanD->getTemplateParameters()->getParam(0)); +auto *CanTypeP = +cast(CanD->getTemplateParameters()->getParam(1)); +auto *CanTemplateP = cast( +CanD->getTemplateParameters()->getParam(2)); +EXPECT_FALSE(CanNonTypeP->getDefaultArgStorage().isInherited()); +EXPECT_FALSE(CanTypeP->getDefaultArgStorage().isInherited()); +EXPECT_FALSE(CanTemplateP->getDefaultArgStorage().isInherited()); +for (Decl *Redecl : D->redecls()) { + auto *ReD = cast(Redecl); + if (ReD != CanD) { +auto *NonTypeP = cast( +ReD->getTemplateParameters()->getParam(0)); +auto *TypeP = cast( +ReD->getTemplateParameters()->getParam(1)); +auto *TemplateP = cast( +ReD->getTemplateParameters()->getParam(2)); +EXPECT_TRUE(NonTypeP->getDefa
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
https://github.com/steakhal created https://github.com/llvm/llvm-project/pull/100990 Actually, on the failure branch of `fopen`, the resulting pointer could alias with `stdout` iff `stdout` is already known to be null. We crashed in this case as the implementation assumed that the state-split for creating the success and failure branches both should be viable; thus dereferenced both of those states - leading to the crash. To fix this, let's just only add this no-alias property for the success path, and that's it :) Fixes #100901 >From 12ff3274fce8dfe534e71abb9511d6549e32f74c Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:33:55 +0200 Subject: [PATCH 1/5] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' Actually, on the failure branch of `fopen`, the resulting pointer could alias with `stdout` iff `stdout` is already known to be null. We crashed in this case as the implementation assumed that the state-split for creating the success and failure branches both should be viable; thus dereferenced both of those states - leading to the crash. To fix this, let's just only add this no-alias property for the success path, and that's it :) Fixes #100901 --- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp | 3 ++- clang/test/Analysis/stream.c| 10 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 53770532609d5..942e7541a83cd 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -938,7 +938,6 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, assert(RetSym && "RetVal must be a symbol here."); State = State->BindExpr(CE, C.getLocationContext(), RetVal); - State = assumeNoAliasingWithStdStreams(State, RetVal, C); // Bifurcate the state into two: one with a valid FILE* pointer, the other // with a NULL. @@ -951,6 +950,8 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, StateNull = StateNull->set(RetSym, StreamState::getOpenFailed(Desc)); + StateNotNull = assumeNoAliasingWithStdStreams(StateNotNull, RetVal, C); + C.addTransition(StateNotNull, constructLeakNoteTag(C, RetSym, "Stream opened here")); C.addTransition(StateNull); diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c index b3a47ce4153d3..575b32d97be31 100644 --- a/clang/test/Analysis/stream.c +++ b/clang/test/Analysis/stream.c @@ -502,11 +502,19 @@ void gh_93408_regression_ZeroSized(struct ZeroSized *buffer) { extern FILE *stdout_like_ptr; void no_aliasing(void) { FILE *f = fopen("file", "r"); + if (!f) return; clang_analyzer_eval(f == stdin); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stderr); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout_like_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} - if (f && f != stdout) { + if (f != stdout) { fclose(f); } } // no-leak: 'fclose()' is always called because 'f' cannot be 'stdout'. + +void only_success_path_does_not_alias_with_stdout(void) { + if (stdout) return; + FILE *f = fopen("/tmp/foof", "r"); // no-crash + if (!f) return; + fclose(f); +} >From 7453968ac1764adbc70f867d43fa3d63473b09f3 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:39:03 +0200 Subject: [PATCH 2/5] NFC Fixup previous PR comment Addresses: https://github.com/llvm/llvm-project/pull/100085#discussion_r1688051166 --- clang/test/Analysis/stream.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c index 575b32d97be31..aff884f190c8e 100644 --- a/clang/test/Analysis/stream.c +++ b/clang/test/Analysis/stream.c @@ -499,14 +499,14 @@ void gh_93408_regression_ZeroSized(struct ZeroSized *buffer) { fclose(f); } -extern FILE *stdout_like_ptr; -void no_aliasing(void) { +extern FILE *non_standard_stream_ptr; +void test_fopen_does_not_alias_with_standard_streams(void) { FILE *f = fopen("file", "r"); if (!f) return; clang_analyzer_eval(f == stdin); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stderr); // expected-warning {{FALSE}} no-TRUE - clang_analyzer_eval(f == stdout_like_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} + clang_analyzer_eval(f == non_standard_stream_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} if (f != stdout) { fclose(f); } >From db92245ab09f195cbb859d85f2b93a81fd1b2617 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: Balazs Benics (steakhal) Changes Actually, on the failure branch of `fopen`, the resulting pointer could alias with `stdout` iff `stdout` is already known to be null. We crashed in this case as the implementation assumed that the state-split for creating the success and failure branches both should be viable; thus dereferenced both of those states - leading to the crash. To fix this, let's just only add this no-alias property for the success path, and that's it :) Fixes #100901 --- Full diff: https://github.com/llvm/llvm-project/pull/100990.diff 3 Files Affected: - (modified) clang/docs/analyzer/checkers.rst (+5-8) - (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+10-18) - (modified) clang/test/Analysis/stream.c (+31-11) ``diff diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index 76a9aae170893..452948aa2cb00 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -1703,7 +1703,11 @@ are detected: * Invalid 3rd ("``whence``") argument to ``fseek``. The stream operations are by this checker usually split into two cases, a success -and a failure case. However, in the case of write operations (like ``fwrite``, +and a failure case. +On the success case it also assumes that the current value of ``stdout``, +``stderr``, or ``stdin`` can't be equal to the file pointer returned by ``fopen``. + +In the case of write operations (like ``fwrite``, ``fprintf`` and even ``fsetpos``) this behavior could produce a large amount of unwanted reports on projects that don't have error checks around the write operations, so by default the checker assumes that write operations always succeed. @@ -1766,13 +1770,6 @@ are assumed to succeed.) fclose(p); } -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). - .. _osx-checkers: osx diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 53770532609d5..4454f30630e27 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -615,30 +615,22 @@ class StreamChecker : public Checker OptInt = -tryExpandAsInteger("EOF", C.getPreprocessor())) +if (const std::optional OptInt = tryExpandAsInteger("EOF", PP)) EofVal = *OptInt; else EofVal = -1; -if (const std::optional OptInt = -tryExpandAsInteger("SEEK_SET", C.getPreprocessor())) +if (const std::optional OptInt = tryExpandAsInteger("SEEK_SET", PP)) SeekSetVal = *OptInt; -if (const std::optional OptInt = -tryExpandAsInteger("SEEK_END", C.getPreprocessor())) +if (const std::optional OptInt = tryExpandAsInteger("SEEK_END", PP)) SeekEndVal = *OptInt; -if (const std::optional OptInt = -tryExpandAsInteger("SEEK_CUR", C.getPreprocessor())) +if (const std::optional OptInt = tryExpandAsInteger("SEEK_CUR", PP)) SeekCurVal = *OptInt; } - void initVaListType(CheckerContext &C) const { -VaListType = C.getASTContext().getBuiltinVaListType().getCanonicalType(); - } - /// Searches for the ExplodedNode where the file descriptor was acquired for /// StreamSym. static const ExplodedNode *getAcquisitionSite(const ExplodedNode *N, @@ -880,9 +872,6 @@ static ProgramStateRef escapeArgs(ProgramStateRef State, CheckerContext &C, void StreamChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const { - initMacroValues(C); - initVaListType(C); - const FnDescription *Desc = lookupFn(Call); if (!Desc || !Desc->PreFn) return; @@ -938,7 +927,6 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, assert(RetSym && "RetVal must be a symbol here."); State = State->BindExpr(CE, C.getLocationContext(), RetVal); - State = assumeNoAliasingWithStdStreams(State, RetVal, C); // Bifurcate the state into two: one with a valid FILE* pointer, the other // with a NULL. @@ -951,6 +939,8 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, StateNull = StateNull->set(RetSym, StreamState::getOpenFailed(Desc)); + StateNotNull = assumeNoAliasingWithStdStreams(StateNotNull, RetVal, C); + C.addTransition(StateNotNull, constructLeakNoteTag(C, RetSym, "Stream opened here")); C.addTransition(StateNull); @@ -2081,10 +2071,12 @@ getGlobalStreamPointerByName(const TranslationUnitDecl *TU, StringRef VarName) { } void StreamChecker::checkASTDecl(const TranslationUnitDecl *TU, -
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1766,13 +1770,6 @@ are assumed to succeed.) fclose(p); } -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). steakhal wrote: I wasn't sure of this section, so I just removed it. Let me know if it's still relevant or not. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
steakhal wrote: I decided to put the fixup NFC changes along with this PR (the ones were submitted after I merged the original commit), but on hindsight probably it would be better to merge those NFC changes separately. If you request, I'll split the PR. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
vabridgers wrote: Thanks for the comments. I do not mind abandoning this change in favor of a better solution. Please let me know when you have posted an improved PR and I'll abandon this one. Best https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] RFC: [cmake] Export CLANG_RESOURCE_DIR in ClangConfig (PR #97197)
kimgr wrote: @tstellar @tuliom It seems to me _almost_ all callers pass `CLANG_RESOURCE_DIR` for the `CustomResourceDir` optional argument: https://github.com/search?q=repo%3Allvm%2Fllvm-project%20Driver%3A%3AGetResourcesPath&type=code the one exception being: https://github.com/llvm/llvm-project/blob/d72c8b02802c87386f5db3c7de6c79e921618fa3/clang/tools/libclang/CIndexer.cpp#L156 I wonder if that last one is a bug...? If so, it seems it would be better to just fold `CLANG_RESOURCE_DIR` into `Driver::GetResourcesPath` and remove the optional argument. https://github.com/llvm/llvm-project/pull/97197 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
steakhal wrote: Thanks for the really valuable reduced case @vabridgers. I'll close this in favor of #100990 if you don't mind. Thanks again for reporting the crash. https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
https://github.com/steakhal closed https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Avoid crashes in the stream checker (PR #100901)
vabridgers wrote: Thanks @steakhal ! https://github.com/llvm/llvm-project/pull/100901 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[Clang] Demote always_inline error to warning for mismatching SME attrs" (PR #100991)
https://github.com/sdesmalen-arm created https://github.com/llvm/llvm-project/pull/100991 Reverts llvm/llvm-project#100740 >From e3e9cde46626ff525442b21963c03675c6bfa368 Mon Sep 17 00:00:00 2001 From: Sander de Smalen Date: Mon, 29 Jul 2024 10:18:27 +0100 Subject: [PATCH] =?UTF-8?q?Revert=20"[Clang]=20Demote=20always=5Finline=20?= =?UTF-8?q?error=20to=20warning=20for=20mismatching=20SME=20att=E2=80=A6"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 5430f73b501f9fc0a38c3768592f5f31bcbdf2f0. --- clang/include/clang/Basic/DiagnosticFrontendKinds.td| 3 --- clang/lib/CodeGen/Targets/AArch64.cpp | 6 ++ clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c | 6 +++--- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 8a1462c670d68..12a4617c64d87 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,9 +288,6 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; -def warn_function_always_inline_attribute_mismatch : Warning< - "always_inline function %1 and its caller %0 have mismatching %2 attributes, " - "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index 1dec3cd40ebd2..b9df54b0c67c4 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,10 +883,8 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report( -CallLoc, CalleeIsStreaming - ? diag::err_function_always_inline_attribute_mismatch - : diag::warn_function_always_inline_attribute_mismatch) +CGM.getDiags().Report(CallLoc, + diag::err_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 98370a888ac6c..25aebeced9379 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -20,7 +20,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +29,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); @@ -39,7 +39,7 @@ void caller_streaming(void) __arm_streaming { #ifdef TEST_LOCALLY __arm_locally_streaming void caller_local(void) { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe
[clang] Revert "[Clang] Demote always_inline error to warning for mismatching SME attrs" (PR #100991)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen @llvm/pr-subscribers-clang Author: Sander de Smalen (sdesmalen-arm) Changes Reverts llvm/llvm-project#100740 --- Full diff: https://github.com/llvm/llvm-project/pull/100991.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (-3) - (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+2-4) - (modified) clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c (+3-3) ``diff diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 8a1462c670d68..12a4617c64d87 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,9 +288,6 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; -def warn_function_always_inline_attribute_mismatch : Warning< - "always_inline function %1 and its caller %0 have mismatching %2 attributes, " - "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index 1dec3cd40ebd2..b9df54b0c67c4 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,10 +883,8 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report( -CallLoc, CalleeIsStreaming - ? diag::err_function_always_inline_attribute_mismatch - : diag::warn_function_always_inline_attribute_mismatch) +CGM.getDiags().Report(CallLoc, + diag::err_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 98370a888ac6c..25aebeced9379 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -20,7 +20,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +29,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); @@ -39,7 +39,7 @@ void caller_streaming(void) __arm_streaming { #ifdef TEST_LOCALLY __arm_locally_streaming void caller_local(void) { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); `` https://github.com/llvm/llvm-project/pull/100991 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] e3a3397 - Revert "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991)
Author: Sander de Smalen Date: 2024-07-29T10:19:28+01:00 New Revision: e3a3397209fe05ec65d74e9096347fc7a76e919e URL: https://github.com/llvm/llvm-project/commit/e3a3397209fe05ec65d74e9096347fc7a76e919e DIFF: https://github.com/llvm/llvm-project/commit/e3a3397209fe05ec65d74e9096347fc7a76e919e.diff LOG: Revert "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) Reverts llvm/llvm-project#100740 Added: Modified: clang/include/clang/Basic/DiagnosticFrontendKinds.td clang/lib/CodeGen/Targets/AArch64.cpp clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c Removed: diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 8a1462c670d68..12a4617c64d87 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,9 +288,6 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; -def warn_function_always_inline_attribute_mismatch : Warning< - "always_inline function %1 and its caller %0 have mismatching %2 attributes, " - "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index 1dec3cd40ebd2..b9df54b0c67c4 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,10 +883,8 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report( -CallLoc, CalleeIsStreaming - ? diag::err_function_always_inline_attribute_mismatch - : diag::warn_function_always_inline_attribute_mismatch) +CGM.getDiags().Report(CallLoc, + diag::err_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 98370a888ac6c..25aebeced9379 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -20,7 +20,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +29,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); @@ -39,7 +39,7 @@ void caller_streaming(void) __arm_streaming { #ifdef TEST_LOCALLY __arm_locally_streaming void caller_local(void) { -inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes, inlining may change runtime behaviour}} +inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[Clang] Demote always_inline error to warning for mismatching SME attrs" (PR #100991)
https://github.com/sdesmalen-arm closed https://github.com/llvm/llvm-project/pull/100991 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
https://github.com/ilya-biryukov edited https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
https://github.com/ilya-biryukov commented: Thanks for the change! This looks like an improvement, but I suspect we can do even better. See the comments I've left in the code. https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
@@ -3747,6 +3747,16 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct) << /*return*/ 1 << /*out of */ 0); + // using plain return in a coroutine is not allowed. + FunctionScopeInfo *FSI = getCurFunction(); + if (getLangOpts().Coroutines && FSI->isCoroutine()) { ilya-biryukov wrote: The `getLangOpts().Coroutines` check looks redundant. I don't think we can ever produce a coroutine in the AST if `getLangOpts().Coroutines == false`, or do we? ```suggestion if (FSI->isCoroutine()) { ``` https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
@@ -291,6 +294,38 @@ void mixed_coreturn_template2(bool b, T) { return; // expected-error {{not allowed in coroutine}} } +struct promise_handle; + +struct Handle : std::coroutine_handle { // expected-note 2{{candidate constructor (the implicit copy constructor) not viable}} ilya-biryukov wrote: NIT: for brevity we could use a shorter substring (same below) ```suggestion struct Handle : std::coroutine_handle { // expected-note 2{{not viable}} ``` https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
@@ -3747,6 +3747,16 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct) << /*return*/ 1 << /*out of */ 0); + // using plain return in a coroutine is not allowed. + FunctionScopeInfo *FSI = getCurFunction(); + if (getLangOpts().Coroutines && FSI->isCoroutine()) { ilya-biryukov wrote: Could we only do this when `FSI->FirstReturnLoc.isInvalid() == true` to make sure we do not start producing the error on every return statement? Previously we only produced a single error, and this seems like a useful behavior to keep. Otherwise we're spamming people with error messages. https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
@@ -291,6 +294,38 @@ void mixed_coreturn_template2(bool b, T) { return; // expected-error {{not allowed in coroutine}} } +struct promise_handle; + +struct Handle : std::coroutine_handle { // expected-note 2{{candidate constructor (the implicit copy constructor) not viable}} +// expected-note@-1 2{{candidate constructor (the implicit move constructor) not viable}} +using promise_type = promise_handle; +}; + +struct promise_handle { +Handle get_return_object() noexcept { + { return Handle(std::coroutine_handle::from_promise(*this)); } +} +suspend_never initial_suspend() const noexcept { return {}; } +suspend_never final_suspend() const noexcept { return {}; } +void return_void() const noexcept {} +void unhandled_exception() const noexcept {} +}; + +Handle mixed_return_value() { + co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} + return 0; // expected-error {{return statement not allowed in coroutine}} ilya-biryukov wrote: Could we add tests with multiple returns? We used to have only one error about 'return' not being allowed, but now we can potentially produce multiple (one before any coroutine statements, multiple after). It's worth specifying these aspects of the behavior so they don't accidentally change later without people consciously updating the tests. https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
@@ -1120,7 +1120,7 @@ void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { // [stmt.return.coroutine]p1: // A coroutine shall not enclose a return statement ([stmt.return]). - if (Fn->FirstReturnLoc.isValid()) { + if (Fn->FirstReturnLoc.isValid() && Fn->FirstReturnLoc < Fn->FirstCoroutineStmtLoc) { ilya-biryukov wrote: We now have some asymmetry between the way we handle errors for `co_await` after `return` and for `return` after `co_await`. (Also for other coroutine keywords, but I'll keep only mentioning `co_await` for simplicity). I think we could get rid of that by moving this code into the function that handles `co_await`. It can check `FirstReturnLoc.isValid()` and issue and error in the same way as `return` checks for `FirstCoroutineStmtLoc.isValid()` (which is the implementation of `Fn->isCoroutine()`) and issues an error. https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Surface error for plain return statement in coroutine earlier (PR #100985)
@@ -291,6 +294,38 @@ void mixed_coreturn_template2(bool b, T) { return; // expected-error {{not allowed in coroutine}} } +struct promise_handle; + +struct Handle : std::coroutine_handle { // expected-note 2{{candidate constructor (the implicit copy constructor) not viable}} +// expected-note@-1 2{{candidate constructor (the implicit move constructor) not viable}} +using promise_type = promise_handle; +}; + +struct promise_handle { +Handle get_return_object() noexcept { + { return Handle(std::coroutine_handle::from_promise(*this)); } +} +suspend_never initial_suspend() const noexcept { return {}; } +suspend_never final_suspend() const noexcept { return {}; } +void return_void() const noexcept {} +void unhandled_exception() const noexcept {} +}; + +Handle mixed_return_value() { + co_await a; // expected-note {{function is a coroutine due to use of 'co_await' here}} + return 0; // expected-error {{return statement not allowed in coroutine}} + // expected-error@-1 {{no viable conversion from returned value of type}} ilya-biryukov wrote: the `-verify` and `expected-error` does not actually let us check the order in which the errors are reported. Could we add another test file that would do something like: ``` // RUN: %clang_cc1 -fsyntax-only %s 2>& 1 | FileCheck // The error about a function not being a coroutine is usually more relevant than the conversion error. // Check that we show it first. // CHECK-NOT: cannot convert // CHECK: return statement not allowed in coroutine // CHECK: cannot convert ``` it does not have to be detailed, just to make sure we actually managed to keep the errors in that order https://github.com/llvm/llvm-project/pull/100985 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] d86311f - [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (#96742)
Author: Dominik Adamski Date: 2024-07-29T11:21:40+02:00 New Revision: d86311f293ebc3867733d4453e0d6c929e620d8b URL: https://github.com/llvm/llvm-project/commit/d86311f293ebc3867733d4453e0d6c929e620d8b DIFF: https://github.com/llvm/llvm-project/commit/d86311f293ebc3867733d4453e0d6c929e620d8b.diff LOG: [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (#96742) Flang-new needs to add `mlink-builtin-bitcode` objects to properly support offload code generation for AMD GPUs (for example, math functions). Both Flang-new and Clang rely on `mlink-builtin-bitcode` flags. These flags are added by the `AMDGPUOpenMPToolchain::addClangTargetOptions` function. Now, both compilers reuse the same function. Flang-new tests for AMDGPU were updated by adding the `-nogpulib` flag. This flag allows running AMDGPU tests on machines without the ROCm stack. Added: Modified: clang/lib/Driver/ToolChains/Flang.cpp flang/test/Driver/omp-driver-offload.f90 flang/test/Driver/target-cpu-features.f90 flang/test/Driver/target-gpu-features.f90 Removed: diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp index c4f2375c64034..f5de5eb23e4be 100644 --- a/clang/lib/Driver/ToolChains/Flang.cpp +++ b/clang/lib/Driver/ToolChains/Flang.cpp @@ -342,6 +342,9 @@ void Flang::AddAMDGPUTargetArgs(const ArgList &Args, StringRef Val = A->getValue(); CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val)); } + + const ToolChain &TC = getToolChain(); + TC.addClangTargetOptions(Args, CmdArgs, Action::OffloadKind::OFK_OpenMP); } void Flang::addTargetOptions(const ArgList &Args, diff --git a/flang/test/Driver/omp-driver-offload.f90 b/flang/test/Driver/omp-driver-offload.f90 index c7cc3bffb43b5..f8876c96d76c9 100644 --- a/flang/test/Driver/omp-driver-offload.f90 +++ b/flang/test/Driver/omp-driver-offload.f90 @@ -14,12 +14,12 @@ ! Test regular -fopenmp with offload, and invocation filtering options ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-HOST-AND-DEVICE ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 --offload-host-device \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-HOST-AND-DEVICE ! OFFLOAD-HOST-AND-DEVICE: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" @@ -29,7 +29,7 @@ ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 --offload-host-only \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-HOST ! OFFLOAD-HOST: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" @@ -39,7 +39,7 @@ ! RUN: %flang -S -### %s 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a --offload-arch=sm_70 --offload-device-only \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OFFLOAD-DEVICE ! OFFLOAD-DEVICE: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" @@ -48,13 +48,13 @@ ! OFFLOAD-DEVICE-NOT: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" ! Test regular -fopenmp with offload for basic fopenmp-is-target-device flag addition and correct fopenmp -! RUN: %flang -### -fopenmp --offload-arch=gfx90a -fopenmp-targets=amdgcn-amd-amdhsa %s 2>&1 | FileCheck --check-prefixes=CHECK-OPENMP-IS-TARGET-DEVICE %s +! RUN: %flang -### -fopenmp --offload-arch=gfx90a -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib %s 2>&1 | FileCheck --check-prefixes=CHECK-OPENMP-IS-TARGET-DEVICE %s ! CHECK-OPENMP-IS-TARGET-DEVICE: "{{[^"]*}}flang-new" "-fc1" {{.*}} "-fopenmp" {{.*}} "-fopenmp-is-target-device" {{.*}}.f90" ! Testing appropriate flags are gnerated and appropriately assigned by the driver when offloading ! RUN: %flang -S -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a \ -! RUN: --target=aarch64-unknown-linux-gnu \ +! RUN: --target=aarch64-unknown-linux-gnu -nogpulib\ ! RUN: | FileCheck %s --check-prefix=OPENMP-OFFLOAD-ARGS ! OPENMP-OFFLOAD-ARGS: "{{[^"]*}}flang-new" "-fc1" "-triple" "aarch64-unknown-linux-gnu" {{.*}} "-fopenmp" {{.*}}.f90" ! OPENMP-OFFLOAD-ARGS-NEXT: "{{[^"]*}}flang-new" "-fc1" "-triple" "amdgcn-amd-amdhsa" @@ -70,19 +70,19 @@ ! RUN: %flang -### %s -o %t 2>&1 \ ! RUN: -fopenmp --offload-arch=gfx90a \ ! RUN: -fopenmp-targets=amdgcn-amd-amdhsa \ -! RUN: -fopenmp-assume-threads-oversubscription \ +! RUN: -fopenmp-assume-threads-oversubscription -nogpulib \ ! RUN: | FileCheck %s --chec
[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)
https://github.com/DominikAdamski closed https://github.com/llvm/llvm-project/pull/96742 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 0362a29 - [clang][dataflow] Fix bug in `buildContainsExprConsumedInDifferentBlock()`. (#100874)
Author: martinboehme Date: 2024-07-29T11:24:26+02:00 New Revision: 0362a29905ab8d68a8eb48741840a514b66552f8 URL: https://github.com/llvm/llvm-project/commit/0362a29905ab8d68a8eb48741840a514b66552f8 DIFF: https://github.com/llvm/llvm-project/commit/0362a29905ab8d68a8eb48741840a514b66552f8.diff LOG: [clang][dataflow] Fix bug in `buildContainsExprConsumedInDifferentBlock()`. (#100874) This was missing a call to `ignoreCFGOmittedNodes()`. As a result, the function would erroneously conclude that a block did not contain an expression consumed in a different block if the expression in question was surrounded by a `ParenExpr` in the consuming block. The patch adds a test that triggers this scenario (and fails without the fix). To prevent this kind of bug in the future, the patch also adds a new method `blockForStmt()` to `AdornedCFG` that calls `ignoreCFGOmittedNodes()` and is preferred over accessing `getStmtToBlock()` directly. Added: Modified: clang/include/clang/Analysis/FlowSensitive/AdornedCFG.h clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp clang/lib/Analysis/FlowSensitive/Transfer.cpp clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp Removed: diff --git a/clang/include/clang/Analysis/FlowSensitive/AdornedCFG.h b/clang/include/clang/Analysis/FlowSensitive/AdornedCFG.h index 420f13ce11bfd..5de66fcb0e3af 100644 --- a/clang/include/clang/Analysis/FlowSensitive/AdornedCFG.h +++ b/clang/include/clang/Analysis/FlowSensitive/AdornedCFG.h @@ -18,6 +18,7 @@ #include "clang/AST/Decl.h" #include "clang/AST/Stmt.h" #include "clang/Analysis/CFG.h" +#include "clang/Analysis/FlowSensitive/ASTOps.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/Error.h" @@ -27,6 +28,24 @@ namespace clang { namespace dataflow { +namespace internal { +class StmtToBlockMap { +public: + StmtToBlockMap(const CFG &Cfg); + + const CFGBlock *lookup(const Stmt &S) const { +return StmtToBlock.lookup(&ignoreCFGOmittedNodes(S)); + } + + const llvm::DenseMap &getMap() const { +return StmtToBlock; + } + +private: + llvm::DenseMap StmtToBlock; +}; +} // namespace internal + /// Holds CFG with additional information derived from it that is needed to /// perform dataflow analysis. class AdornedCFG { @@ -49,8 +68,17 @@ class AdornedCFG { const CFG &getCFG() const { return *Cfg; } /// Returns a mapping from statements to basic blocks that contain them. + /// Deprecated. Use `blockForStmt()` instead (which prevents the potential + /// error of forgetting to call `ignoreCFGOmittedNodes()` on the statement to + /// look up). const llvm::DenseMap &getStmtToBlock() const { -return StmtToBlock; +return StmtToBlock.getMap(); + } + + /// Returns the basic block that contains `S`, or null if no basic block + /// containing `S` is found. + const CFGBlock *blockForStmt(const Stmt &S) const { +return StmtToBlock.lookup(S); } /// Returns whether `B` is reachable from the entry block. @@ -73,8 +101,7 @@ class AdornedCFG { private: AdornedCFG( const Decl &D, std::unique_ptr Cfg, - llvm::DenseMap StmtToBlock, - llvm::BitVector BlockReachable, + internal::StmtToBlockMap StmtToBlock, llvm::BitVector BlockReachable, llvm::DenseSet ContainsExprConsumedInDifferentBlock) : ContainingDecl(D), Cfg(std::move(Cfg)), StmtToBlock(std::move(StmtToBlock)), @@ -85,7 +112,7 @@ class AdornedCFG { /// The `Decl` containing the statement used to construct the CFG. const Decl &ContainingDecl; std::unique_ptr Cfg; - llvm::DenseMap StmtToBlock; + internal::StmtToBlockMap StmtToBlock; llvm::BitVector BlockReachable; llvm::DenseSet ContainsExprConsumedInDifferentBlock; }; diff --git a/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp b/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp index 255543021a998..876b5a3db5249 100644 --- a/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp +++ b/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp @@ -16,6 +16,7 @@ #include "clang/AST/Decl.h" #include "clang/AST/Stmt.h" #include "clang/Analysis/CFG.h" +#include "clang/Analysis/FlowSensitive/ASTOps.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/Error.h" @@ -96,8 +97,7 @@ static llvm::BitVector findReachableBlocks(const CFG &Cfg) { static llvm::DenseSet buildContainsExprConsumedInDifferentBlock( -const CFG &Cfg, -const llvm::DenseMap &StmtToBlock) { +const CFG &Cfg, const internal::StmtToBlockMap &StmtToBlock) { llvm::DenseSet Result; auto CheckChildExprs = [&Result, &StmtToBlock](const Stmt *S, @@ -105,7 +105,7 @@ buildContainsExprConsumedInDifferentBlock( for (const Stmt *Child : S->children()) { if (!isa_and_nonnull(Child)) continue; -
[clang] [clang][dataflow] Fix bug in `buildContainsExprConsumedInDifferentBlock()`. (PR #100874)
https://github.com/martinboehme closed https://github.com/llvm/llvm-project/pull/100874 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
vabridgers wrote: LGTM, someone must approve. Thanks for fixing this! https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
https://github.com/NagyDonat approved this pull request. LGTM. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
https://github.com/NagyDonat edited https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1766,13 +1770,6 @@ are assumed to succeed.) fclose(p); } -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). NagyDonat wrote: Hmm, perhaps keep a note saying "This checker does not track operations that use integer file descriptors instead of `FILE *` pointers". (If I recall correctly this is true and might be relevant for someone who's used to work with low-level stuff.) However it's also completely fine (from my POV) if you delete the whole Limitations section. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1703,7 +1703,11 @@ are detected: * Invalid 3rd ("``whence``") argument to ``fseek``. The stream operations are by this checker usually split into two cases, a success -and a failure case. However, in the case of write operations (like ``fwrite``, +and a failure case. +On the success case it also assumes that the current value of ``stdout``, +``stderr``, or ``stdin`` can't be equal to the file pointer returned by ``fopen``. + +In the case of write operations (like ``fwrite``, NagyDonat wrote: Personally I'd re-wrap the lines; but I can accept this if you think that it's important to minimize the diff footprint. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
NagyDonat wrote: > I decided to put the fixup NFC changes along with this PR (the ones were > submitted after I merged the original commit), but on hindsight probably it > would be better to merge those NFC changes separately. If you request, I'll > split the PR. Feel free to keep the NFC changes in this commit, just briefly mention them in the description ("This commit also contains some minor NFC code quality improvements." or something similar.) https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1703,7 +1703,11 @@ are detected: * Invalid 3rd ("``whence``") argument to ``fseek``. The stream operations are by this checker usually split into two cases, a success -and a failure case. However, in the case of write operations (like ``fwrite``, +and a failure case. +On the success case it also assumes that the current value of ``stdout``, +``stderr``, or ``stdin`` can't be equal to the file pointer returned by ``fopen``. + +In the case of write operations (like ``fwrite``, steakhal wrote: Same feeling. But I decided to opt for minimizing the diff. I still think that I made the right call. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1703,7 +1703,11 @@ are detected: * Invalid 3rd ("``whence``") argument to ``fseek``. The stream operations are by this checker usually split into two cases, a success -and a failure case. However, in the case of write operations (like ``fwrite``, +and a failure case. +On the success case it also assumes that the current value of ``stdout``, +``stderr``, or ``stdin`` can't be equal to the file pointer returned by ``fopen``. + +In the case of write operations (like ``fwrite``, NagyDonat wrote: Ok, then feel free to keep the short diff. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) (PR #100996)
https://github.com/sdesmalen-arm created https://github.com/llvm/llvm-project/pull/100996 Test `aarch64-sme-inline-streaming-attrs.c` caused some buildbot failures, because the test was missing a `REQUIRES: aarch64-registered target`. This was because we've demoted the error to a warning, which then resulted in a different error message, because Clang can't actually CodeGen the IR. >From 692d4b316c74daaf18819095f23c29e4bb808b26 Mon Sep 17 00:00:00 2001 From: Sander de Smalen Date: Mon, 29 Jul 2024 09:34:18 + Subject: [PATCH] Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) Test `aarch64-sme-inline-streaming-attrs.c` caused some buildbot failures, because the test was missing a `REQUIRES: aarch64-registered target`. This was because we've demoted the error to a warning, which then resulted in a different error message, because Clang can't actually CodeGen the IR. --- clang/include/clang/Basic/DiagnosticFrontendKinds.td| 3 +++ clang/lib/CodeGen/Targets/AArch64.cpp | 6 -- clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c | 8 +--- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 12a4617c64d87..8a1462c670d68 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,6 +288,9 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; +def warn_function_always_inline_attribute_mismatch : Warning< + "always_inline function %1 and its caller %0 have mismatching %2 attributes, " + "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index b9df54b0c67c4..1dec3cd40ebd2 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,8 +883,10 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report(CallLoc, - diag::err_function_always_inline_attribute_mismatch) +CGM.getDiags().Report( +CallLoc, CalleeIsStreaming + ? diag::err_function_always_inline_attribute_mismatch + : diag::warn_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 25aebeced9379..9c3d08a25945a 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -3,6 +3,8 @@ // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_STREAMING %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_LOCALLY %s +// REQUIRES: aarch64-registered-target + #define __ai __attribute__((always_inline)) __ai void inlined_fn(void) {} __ai void inlined_fn_streaming_compatible(void) __arm_streaming_compatible {} @@ -20,7 +22,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +31,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour
[clang] Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) (PR #100996)
llvmbot wrote: @llvm/pr-subscribers-backend-aarch64 @llvm/pr-subscribers-clang Author: Sander de Smalen (sdesmalen-arm) Changes Test `aarch64-sme-inline-streaming-attrs.c` caused some buildbot failures, because the test was missing a `REQUIRES: aarch64-registered target`. This was because we've demoted the error to a warning, which then resulted in a different error message, because Clang can't actually CodeGen the IR. --- Full diff: https://github.com/llvm/llvm-project/pull/100996.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+3) - (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+4-2) - (modified) clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c (+5-3) ``diff diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 12a4617c64d87..8a1462c670d68 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,6 +288,9 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; +def warn_function_always_inline_attribute_mismatch : Warning< + "always_inline function %1 and its caller %0 have mismatching %2 attributes, " + "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index b9df54b0c67c4..1dec3cd40ebd2 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,8 +883,10 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report(CallLoc, - diag::err_function_always_inline_attribute_mismatch) +CGM.getDiags().Report( +CallLoc, CalleeIsStreaming + ? diag::err_function_always_inline_attribute_mismatch + : diag::warn_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 25aebeced9379..9c3d08a25945a 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -3,6 +3,8 @@ // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_STREAMING %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_LOCALLY %s +// REQUIRES: aarch64-registered-target + #define __ai __attribute__((always_inline)) __ai void inlined_fn(void) {} __ai void inlined_fn_streaming_compatible(void) __arm_streaming_compatible {} @@ -20,7 +22,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +31,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); @@ -39,7 +41,7 @@ void caller_streaming(void) __arm_streaming { #ifdef TEST_LOCALLY __arm_locally_streaming void caller_local(void) { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline funct
[clang] Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) (PR #100996)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: Sander de Smalen (sdesmalen-arm) Changes Test `aarch64-sme-inline-streaming-attrs.c` caused some buildbot failures, because the test was missing a `REQUIRES: aarch64-registered target`. This was because we've demoted the error to a warning, which then resulted in a different error message, because Clang can't actually CodeGen the IR. --- Full diff: https://github.com/llvm/llvm-project/pull/100996.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+3) - (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+4-2) - (modified) clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c (+5-3) ``diff diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 12a4617c64d87..8a1462c670d68 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,6 +288,9 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; +def warn_function_always_inline_attribute_mismatch : Warning< + "always_inline function %1 and its caller %0 have mismatching %2 attributes, " + "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index b9df54b0c67c4..1dec3cd40ebd2 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,8 +883,10 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report(CallLoc, - diag::err_function_always_inline_attribute_mismatch) +CGM.getDiags().Report( +CallLoc, CalleeIsStreaming + ? diag::err_function_always_inline_attribute_mismatch + : diag::warn_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 25aebeced9379..9c3d08a25945a 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -3,6 +3,8 @@ // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_STREAMING %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_LOCALLY %s +// REQUIRES: aarch64-registered-target + #define __ai __attribute__((always_inline)) __ai void inlined_fn(void) {} __ai void inlined_fn_streaming_compatible(void) __arm_streaming_compatible {} @@ -20,7 +22,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +31,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); @@ -39,7 +41,7 @@ void caller_streaming(void) __arm_streaming { #ifdef TEST_LOCALLY __arm_locally_streaming void caller_local(void) { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_local' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its cal
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1766,13 +1770,6 @@ are assumed to succeed.) fclose(p); } -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). steakhal wrote: Yea, but I didn't know exactly what it refers to. We could add an example for such a case there. That would help. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/100990 >From 12ff3274fce8dfe534e71abb9511d6549e32f74c Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:33:55 +0200 Subject: [PATCH 1/6] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' Actually, on the failure branch of `fopen`, the resulting pointer could alias with `stdout` iff `stdout` is already known to be null. We crashed in this case as the implementation assumed that the state-split for creating the success and failure branches both should be viable; thus dereferenced both of those states - leading to the crash. To fix this, let's just only add this no-alias property for the success path, and that's it :) Fixes #100901 --- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp | 3 ++- clang/test/Analysis/stream.c| 10 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 53770532609d5..942e7541a83cd 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -938,7 +938,6 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, assert(RetSym && "RetVal must be a symbol here."); State = State->BindExpr(CE, C.getLocationContext(), RetVal); - State = assumeNoAliasingWithStdStreams(State, RetVal, C); // Bifurcate the state into two: one with a valid FILE* pointer, the other // with a NULL. @@ -951,6 +950,8 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, StateNull = StateNull->set(RetSym, StreamState::getOpenFailed(Desc)); + StateNotNull = assumeNoAliasingWithStdStreams(StateNotNull, RetVal, C); + C.addTransition(StateNotNull, constructLeakNoteTag(C, RetSym, "Stream opened here")); C.addTransition(StateNull); diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c index b3a47ce4153d3..575b32d97be31 100644 --- a/clang/test/Analysis/stream.c +++ b/clang/test/Analysis/stream.c @@ -502,11 +502,19 @@ void gh_93408_regression_ZeroSized(struct ZeroSized *buffer) { extern FILE *stdout_like_ptr; void no_aliasing(void) { FILE *f = fopen("file", "r"); + if (!f) return; clang_analyzer_eval(f == stdin); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stderr); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout_like_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} - if (f && f != stdout) { + if (f != stdout) { fclose(f); } } // no-leak: 'fclose()' is always called because 'f' cannot be 'stdout'. + +void only_success_path_does_not_alias_with_stdout(void) { + if (stdout) return; + FILE *f = fopen("/tmp/foof", "r"); // no-crash + if (!f) return; + fclose(f); +} >From 7453968ac1764adbc70f867d43fa3d63473b09f3 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:39:03 +0200 Subject: [PATCH 2/6] NFC Fixup previous PR comment Addresses: https://github.com/llvm/llvm-project/pull/100085#discussion_r1688051166 --- clang/test/Analysis/stream.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c index 575b32d97be31..aff884f190c8e 100644 --- a/clang/test/Analysis/stream.c +++ b/clang/test/Analysis/stream.c @@ -499,14 +499,14 @@ void gh_93408_regression_ZeroSized(struct ZeroSized *buffer) { fclose(f); } -extern FILE *stdout_like_ptr; -void no_aliasing(void) { +extern FILE *non_standard_stream_ptr; +void test_fopen_does_not_alias_with_standard_streams(void) { FILE *f = fopen("file", "r"); if (!f) return; clang_analyzer_eval(f == stdin); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stderr); // expected-warning {{FALSE}} no-TRUE - clang_analyzer_eval(f == stdout_like_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} + clang_analyzer_eval(f == non_standard_stream_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} if (f != stdout) { fclose(f); } >From db92245ab09f195cbb859d85f2b93a81fd1b2617 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:46:16 +0200 Subject: [PATCH 3/6] NFC Fixup previous PR comment Addresses https://github.com/llvm/llvm-project/pull/100085#discussion_r1688054004 --- .../StaticAnalyzer/Checkers/StreamChecker.cpp | 25 ++- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 942e7541a83cd..4454f30630e27 100644 --- a/clang/li
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
steakhal wrote: @balazske Could you please have a look? I wanna make sure everyone is aligned. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Support -Wa, options -mmsa and -mno-msa (PR #99615)
@@ -5337,9 +5337,13 @@ def mmadd4 : Flag<["-"], "mmadd4">, Group, def mno_madd4 : Flag<["-"], "mno-madd4">, Group, HelpText<"Disable the generation of 4-operand madd.s, madd.d and related instructions.">; def mmsa : Flag<["-"], "mmsa">, Group, - HelpText<"Enable MSA ASE (MIPS only)">; + Visibility<[ClangOption, CC1AsOption]>, yingopq wrote: Hi @MaskRay, I submitted changes, could you help review again? Thanks. https://github.com/llvm/llvm-project/pull/99615 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1766,13 +1770,6 @@ are assumed to succeed.) fclose(p); } -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). NagyDonat wrote: It refers to functions like `write` [(man page)](https://www.man7.org/linux/man-pages/man2/write.2.html) where the file is specified by an `int` argument. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][dataflow] Handle CXXInheritedCtorInitExpr in ResultObjectVisitor. (PR #99616)
martinboehme wrote: > I have a high-level question not directly related to the patch. We have > probably even talked about it at a conference a few years ago but I don't > remember 😅 I don't recall -- maybe you talked to someone else? > > `ResultObjectVisitor` > > I briefly looked at the implementation and I suspect that you folks might be > reinventing > [`ConstructionContext`](https://clang.llvm.org/doxygen/classclang_1_1ConstructionContext.html) > which is typically¹ already available in the CFG. (Under an off-by-default > CFG build option.) (I'm in favor of turning it on by default.) (Together with > a few other options that improve precision, eg. copy elision and RVO support.) > > __ ¹ Not all of the 30+ possible construction contexts are currently > implemented. But your visitor doesn't seem to implement them either. Thanks for the info -- I wasn't aware of `ConstructionContext`. Will take a look. Can you point me to some examples of how this is used? Agree that we should use `ConstructionContext` in favor of `ResultObjectVisitor` if feasible. https://github.com/llvm/llvm-project/pull/99616 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
@@ -1766,13 +1770,6 @@ are assumed to succeed.) fclose(p); } -**Limitations** - -The checker does not track the correspondence between integer file descriptors -and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not -treated specially and are therefore often not recognized (because these streams -are usually not opened explicitly by the program, and are global variables). steakhal wrote: Ah indeed. So basically opening a file with file descriptor "ints" and then using `fdopen()` to get the corresponding `FILE *` - and back with `fileno()`. Yea, that seems weird to do :D Probably has its use somewhere though. Anyways, makes sense now. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang][LLVM][AArch64] Add intrinsic for MOVT SME2 instruction (PR #97602)
https://github.com/CarolineConcatto updated https://github.com/llvm/llvm-project/pull/97602 >From 70d1ec0e1c1bd896cf753510a8452325b086430e Mon Sep 17 00:00:00 2001 From: Caroline Concatto Date: Wed, 3 Jul 2024 15:55:45 + Subject: [PATCH 1/4] [Clang][LLVM][AArch64] Add intrinsic for MOVT SME2 instruction This patch adds these intrinsics: // Variants are also available for: // [_s8], [_u16], [_s16], [_u32], [_s32], [_u64], [_s64] // [_bf16], [_f16], [_f32], [_f64] void svwrite_lane_zt[_u8](uint64_t zt0, svuint8_t zt, uint64_t idx) __arm_streaming __arm_inout("zt0"); void svwrite_zt[_u8](uint64_t zt0, svuint8_t zt) __arm_streaming __arm_inout("zt0"); according to PR#324[1] [1]https://github.com/ARM-software/acle/pull/324 --- clang/include/clang/Basic/arm_sme.td | 5 + .../acle_sme2_write_lane_zt.c | 401 ++ .../aarch64-sme2-intrinsics/acle_sme2_imm.cpp | 10 +- llvm/include/llvm/IR/IntrinsicsAArch64.td | 9 + .../Target/AArch64/AArch64ISelLowering.cpp| 2 + .../lib/Target/AArch64/AArch64SMEInstrInfo.td | 2 +- llvm/lib/Target/AArch64/SMEInstrFormats.td| 42 +- .../AArch64/sme2-intrinsics-read-zt.ll| 162 +++ 8 files changed, 630 insertions(+), 3 deletions(-) create mode 100644 clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_write_lane_zt.c create mode 100644 llvm/test/CodeGen/AArch64/sme2-intrinsics-read-zt.ll diff --git a/clang/include/clang/Basic/arm_sme.td b/clang/include/clang/Basic/arm_sme.td index ce8908f566f2f..ff68e536e99b0 100644 --- a/clang/include/clang/Basic/arm_sme.td +++ b/clang/include/clang/Basic/arm_sme.td @@ -817,4 +817,9 @@ multiclass ZAReadzArray{ defm SVREADZ_VG2 : ZAReadzArray<"2">; defm SVREADZ_VG4 : ZAReadzArray<"4">; + +let SMETargetGuard = "sme2,sme-lutv2" in { + def SVWRITE_LANE_ZT : SInst<"svwrite_lane_zt[_{d}]", "vidi", "cUcsUsiUilUlfhdb", MergeNone, "aarch64_sme_write_lane_zt", [IsStreaming, IsInOutZT0], [ImmCheck<0, ImmCheck0_0>, ImmCheck<2, ImmCheck0_3>]>; + def SVWRITE_ZT : SInst<"svwrite_zt[_{d}]", "vid", "cUcsUsiUilUlfhdb", MergeNone, "aarch64_sme_write_zt", [IsStreaming, IsInOutZT0], [ImmCheck<0, ImmCheck0_0>]>; +} } // let SVETargetGuard = InvalidMode diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_write_lane_zt.c b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_write_lane_zt.c new file mode 100644 index 0..9bdc3481953a2 --- /dev/null +++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_write_lane_zt.c @@ -0,0 +1,401 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 5 +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -x c++ -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX +// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -x c++ -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX + +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -S -Werror -Wall -o /dev/null %s +// REQUIRES: aarch64-registered-target + +#ifdef SVE_OVERLOADED_FORMS +#define SVE_ACLE_FUNC(A1,A2_UNUSED) A1 +#else +#define SVE_ACLE_FUNC(A1,A2) A1##A2 +#endif + +#include + +// CHECK-LABEL: define dso_local void @test_write_lane_zt_u8_1( +// CHECK-SAME: [[V:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:tail call void @llvm.aarch64.sme.write.lane.zt.nxv16i8(i32 0, [[V]], i32 1) +// CHECK-NEXT:ret void +// +// CHECK-CXX-LABEL: define dso_local void @_Z23test_write_lane_zt_u8_1u11__SVUint8_t( +// CHECK-CXX-SAME: [[V:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-CXX-NEXT: [[ENTRY:.*:]] +// CHECK-CXX-NEXT:tail call void @llvm.aarch64.sme.write.lane.zt.nxv16i8(i32 0, [[V]], i32 1) +// CHECK-CXX-NEXT:ret void +// +void test_write_lane_zt_u8_1(svuint8_t v) __arm_streaming __arm_inout("zt0") { + SVE_ACLE_FUNC(svwrite_lane_zt, _u8)(0, v, 1); +} + +// CHECK-LABEL: define dso_local void @test_write_lane_zt_s8_2( +// CHECK-SAME: [[V:%.*]]) local_unnamed_addr #[[ATTR0]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:tail call void @llvm.aarch64.sme.write.lane.zt.nxv16i8(i32 0, [[V]], i32 2) +// CHECK-NEXT:ret void +// +// CHECK-CXX-LABEL:
[clang] [Clang][OpenMP] Allow `num_teams` to accept multiple expressions (PR #99732)
@@ -3793,8 +3793,8 @@ bool RecursiveASTVisitor::VisitOMPMapClause(OMPMapClause *C) { template bool RecursiveASTVisitor::VisitOMPNumTeamsClause( OMPNumTeamsClause *C) { + TRY_TO(VisitOMPClauseList(C)); TRY_TO(VisitOMPClauseWithPreInit(C)); alexey-bataev wrote: IIRC, it is part of VisitOMPClauseList https://github.com/llvm/llvm-project/pull/99732 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 389679d - Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) (#100996)
Author: Sander de Smalen Date: 2024-07-29T11:23:25+01:00 New Revision: 389679d5f9055bffe8bbd25ae41f084a8d08e0f8 URL: https://github.com/llvm/llvm-project/commit/389679d5f9055bffe8bbd25ae41f084a8d08e0f8 DIFF: https://github.com/llvm/llvm-project/commit/389679d5f9055bffe8bbd25ae41f084a8d08e0f8.diff LOG: Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) (#100996) Test `aarch64-sme-inline-streaming-attrs.c` caused some buildbot failures, because the test was missing a `REQUIRES: aarch64-registered target`. This was because we've demoted the error to a warning, which then resulted in a different error message, because Clang can't actually CodeGen the IR. Added: Modified: clang/include/clang/Basic/DiagnosticFrontendKinds.td clang/lib/CodeGen/Targets/AArch64.cpp clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c Removed: diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 12a4617c64d87..8a1462c670d68 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -288,6 +288,9 @@ def err_function_needs_feature : Error< let CategoryName = "Codegen ABI Check" in { def err_function_always_inline_attribute_mismatch : Error< "always_inline function %1 and its caller %0 have mismatching %2 attributes">; +def warn_function_always_inline_attribute_mismatch : Warning< + "always_inline function %1 and its caller %0 have mismatching %2 attributes, " + "inlining may change runtime behaviour">, InGroup; def err_function_always_inline_new_za : Error< "always_inline function %0 has new za state">; diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index b9df54b0c67c4..1dec3cd40ebd2 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -883,8 +883,10 @@ void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming( if (!CalleeIsStreamingCompatible && (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) -CGM.getDiags().Report(CallLoc, - diag::err_function_always_inline_attribute_mismatch) +CGM.getDiags().Report( +CallLoc, CalleeIsStreaming + ? diag::err_function_always_inline_attribute_mismatch + : diag::warn_function_always_inline_attribute_mismatch) << Caller->getDeclName() << Callee->getDeclName() << "streaming"; if (auto *NewAttr = Callee->getAttr()) if (NewAttr->isNewZA()) diff --git a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c index 25aebeced9379..9c3d08a25945a 100644 --- a/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c +++ b/clang/test/CodeGen/aarch64-sme-inline-streaming-attrs.c @@ -3,6 +3,8 @@ // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_STREAMING %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -o /dev/null -target-feature +sme -verify -DTEST_LOCALLY %s +// REQUIRES: aarch64-registered-target + #define __ai __attribute__((always_inline)) __ai void inlined_fn(void) {} __ai void inlined_fn_streaming_compatible(void) __arm_streaming_compatible {} @@ -20,7 +22,7 @@ void caller(void) { #ifdef TEST_COMPATIBLE void caller_compatible(void) __arm_streaming_compatible { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_compatible' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); // expected-error {{always_inline function 'inlined_fn_streaming' and its caller 'caller_compatible' have mismatching streaming attributes}} inlined_fn_local(); // expected-error {{always_inline function 'inlined_fn_local' and its caller 'caller_compatible' have mismatching streaming attributes}} @@ -29,7 +31,7 @@ void caller_compatible(void) __arm_streaming_compatible { #ifdef TEST_STREAMING void caller_streaming(void) __arm_streaming { -inlined_fn(); // expected-error {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes}} +inlined_fn(); // expected-warning {{always_inline function 'inlined_fn' and its caller 'caller_streaming' have mismatching streaming attributes, inlining may change runtime behaviour}} inlined_fn_streaming_compatible(); inlined_fn_streaming(); inlined_fn_local(); @@ -39,7 +41,7 @@ void caller_streaming(void) __arm_streaming { #ifdef TEST_LOCALLY __arm_locall
[clang] Reland: "[Clang] Demote always_inline error to warning for mismatching SME attrs" (#100991) (PR #100996)
https://github.com/sdesmalen-arm closed https://github.com/llvm/llvm-project/pull/100996 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][OpenMP] Allow `num_teams` to accept multiple expressions (PR #99732)
@@ -21587,32 +21597,39 @@ const ValueDecl *SemaOpenMP::getOpenMPDeclareMapperVarName() const { return cast(DSAStack->getDeclareMapperVarRef())->getDecl(); } -OMPClause *SemaOpenMP::ActOnOpenMPNumTeamsClause(Expr *NumTeams, +OMPClause *SemaOpenMP::ActOnOpenMPNumTeamsClause(ArrayRef VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { - Expr *ValExpr = NumTeams; - Stmt *HelperValStmt = nullptr; - - // OpenMP [teams Constrcut, Restrictions] - // The num_teams expression must evaluate to a positive integer value. - if (!isNonNegativeIntegerValue(ValExpr, SemaRef, OMPC_num_teams, - /*StrictlyPositive=*/true)) + if (VarList.empty()) return nullptr; + for (Expr *ValExpr : VarList) { +// OpenMP [teams Constrcut, Restrictions] +// The num_teams expression must evaluate to a positive integer value. +if (!isNonNegativeIntegerValue(ValExpr, SemaRef, OMPC_num_teams, + /*StrictlyPositive=*/true)) + return nullptr; + } + OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( DKind, OMPC_num_teams, getLangOpts().OpenMP); - if (CaptureRegion != OMPD_unknown && - !SemaRef.CurContext->isDependentContext()) { + if (CaptureRegion == OMPD_unknown || SemaRef.CurContext->isDependentContext()) +return OMPNumTeamsClause::Create(getASTContext(), StartLoc, LParenLoc, + EndLoc, VarList, /*PreInit=*/nullptr); + + llvm::MapVector Captures; + SmallVector Vars; + for (Expr *ValExpr : VarList) { ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); -llvm::MapVector Captures; ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); -HelperValStmt = buildPreInits(getASTContext(), Captures); +Vars.push_back(ValExpr); } - return new (getASTContext()) OMPNumTeamsClause( - ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); alexey-bataev wrote: Here CaptureRegion is set, but you dropped it and because of this the expression started being passed by reference instead of by value https://github.com/llvm/llvm-project/pull/99732 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Disallow applying `onwership_returns` to functions that return non-pointers (PR #99564)
pskrgag wrote: Applied style and spelling fixes, thank you for review! https://github.com/llvm/llvm-project/pull/99564 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Sanitizer] Make sanitizer passes idempotent (PR #99439)
https://github.com/skc7 updated https://github.com/llvm/llvm-project/pull/99439 >From 2bcca883eae902238cb49d44ed24aa1304364646 Mon Sep 17 00:00:00 2001 From: skc7 Date: Thu, 18 Jul 2024 11:49:24 +0530 Subject: [PATCH 1/2] [Sanitizer] Make sanitizer passes idempotent. --- clang/test/CodeGenObjC/no-sanitize.m | 2 +- .../Instrumentation/AddressSanitizer.cpp | 6 ++ .../Instrumentation/DataFlowSanitizer.cpp | 4 ++ .../Instrumentation/HWAddressSanitizer.cpp| 4 ++ .../Instrumentation/MemorySanitizer.cpp | 4 ++ .../Instrumentation/ThreadSanitizer.cpp | 4 ++ .../AddressSanitizer/asan-pass-second-run.ll | 55 +++ .../AddressSanitizer/missing_dbg.ll | 2 +- .../dfsan-pass-second-run.ll | 17 ++ .../hwasan-pass-second-run.ll | 41 ++ .../MemorySanitizer/msan-pass-second-run.ll | 43 +++ .../ThreadSanitizer/tsan-pass-second-run.ll | 28 ++ 12 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 llvm/test/Instrumentation/AddressSanitizer/asan-pass-second-run.ll create mode 100644 llvm/test/Instrumentation/DataFlowSanitizer/dfsan-pass-second-run.ll create mode 100644 llvm/test/Instrumentation/HWAddressSanitizer/hwasan-pass-second-run.ll create mode 100644 llvm/test/Instrumentation/MemorySanitizer/msan-pass-second-run.ll create mode 100644 llvm/test/Instrumentation/ThreadSanitizer/tsan-pass-second-run.ll diff --git a/clang/test/CodeGenObjC/no-sanitize.m b/clang/test/CodeGenObjC/no-sanitize.m index abaf6fab26ab6..b5c6a5ad745f3 100644 --- a/clang/test/CodeGenObjC/no-sanitize.m +++ b/clang/test/CodeGenObjC/no-sanitize.m @@ -2,7 +2,7 @@ @interface I0 @end @implementation I0 -// CHECK-NOT: sanitize_address +// CHECK-NOT: Function Attrs: sanitize_address - (void) im0: (int) a0 __attribute__((no_sanitize("address"))) { int (^blockName)(void) = ^int(void) { return 0; }; } diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp index 9fb1df7ab2b79..bed43db1cc487 100644 --- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp +++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp @@ -1251,6 +1251,12 @@ AddressSanitizerPass::AddressSanitizerPass( PreservedAnalyses AddressSanitizerPass::run(Module &M, ModuleAnalysisManager &MAM) { + // Return early if nosanitize_address module flag is present for the module. + // This implies that asan pass has already run before. + if (M.getModuleFlag("nosanitize_address")) +return PreservedAnalyses::all(); + M.addModuleFlag(Module::ModFlagBehavior::Override, "nosanitize_address", 1); + ModuleAddressSanitizer ModuleSanitizer( M, Options.InsertVersionCheck, Options.CompileKernel, Options.Recover, UseGlobalGC, UseOdrIndicator, DestructorKind, ConstructorKind); diff --git a/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp index 113d39b4f2af7..1fe8ef9e61284 100644 --- a/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp +++ b/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp @@ -3473,6 +3473,10 @@ void DFSanVisitor::visitPHINode(PHINode &PN) { PreservedAnalyses DataFlowSanitizerPass::run(Module &M, ModuleAnalysisManager &AM) { + // Return early if nosanitize_dataflow module flag is present for the module. + if (M.getModuleFlag("nosanitize_dataflow")) +return PreservedAnalyses::all(); + M.addModuleFlag(Module::ModFlagBehavior::Override, "nosanitize_dataflow", 1); auto GetTLI = [&](Function &F) -> TargetLibraryInfo & { auto &FAM = AM.getResult(M).getManager(); diff --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp index 812874ff3c173..6615cbdd2d41d 100644 --- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp +++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp @@ -455,6 +455,10 @@ class HWAddressSanitizer { PreservedAnalyses HWAddressSanitizerPass::run(Module &M, ModuleAnalysisManager &MAM) { + // Return early if nosanitize_hwaddress module flag is present for the module. + if (M.getModuleFlag("nosanitize_hwaddress")) +return PreservedAnalyses::all(); + M.addModuleFlag(Module::ModFlagBehavior::Override, "nosanitize_hwaddress", 1); const StackSafetyGlobalInfo *SSI = nullptr; auto TargetTriple = llvm::Triple(M.getTargetTriple()); if (shouldUseStackSafetyAnalysis(TargetTriple, Options.DisableOptimization)) diff --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp index 910c36faf7e0f..4d456fe20b629 100644 --- a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp +++ b/llvm
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
https://github.com/balazske approved this pull request. This looks good now, documentation could be a bit more exact in that operations on standard streams are not checked by the checker, like any other operation on streams that are not opened on the analysis path. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/100990 >From 12ff3274fce8dfe534e71abb9511d6549e32f74c Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:33:55 +0200 Subject: [PATCH 1/7] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' Actually, on the failure branch of `fopen`, the resulting pointer could alias with `stdout` iff `stdout` is already known to be null. We crashed in this case as the implementation assumed that the state-split for creating the success and failure branches both should be viable; thus dereferenced both of those states - leading to the crash. To fix this, let's just only add this no-alias property for the success path, and that's it :) Fixes #100901 --- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp | 3 ++- clang/test/Analysis/stream.c| 10 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 53770532609d5..942e7541a83cd 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -938,7 +938,6 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, assert(RetSym && "RetVal must be a symbol here."); State = State->BindExpr(CE, C.getLocationContext(), RetVal); - State = assumeNoAliasingWithStdStreams(State, RetVal, C); // Bifurcate the state into two: one with a valid FILE* pointer, the other // with a NULL. @@ -951,6 +950,8 @@ void StreamChecker::evalFopen(const FnDescription *Desc, const CallEvent &Call, StateNull = StateNull->set(RetSym, StreamState::getOpenFailed(Desc)); + StateNotNull = assumeNoAliasingWithStdStreams(StateNotNull, RetVal, C); + C.addTransition(StateNotNull, constructLeakNoteTag(C, RetSym, "Stream opened here")); C.addTransition(StateNull); diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c index b3a47ce4153d3..575b32d97be31 100644 --- a/clang/test/Analysis/stream.c +++ b/clang/test/Analysis/stream.c @@ -502,11 +502,19 @@ void gh_93408_regression_ZeroSized(struct ZeroSized *buffer) { extern FILE *stdout_like_ptr; void no_aliasing(void) { FILE *f = fopen("file", "r"); + if (!f) return; clang_analyzer_eval(f == stdin); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stderr); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout_like_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} - if (f && f != stdout) { + if (f != stdout) { fclose(f); } } // no-leak: 'fclose()' is always called because 'f' cannot be 'stdout'. + +void only_success_path_does_not_alias_with_stdout(void) { + if (stdout) return; + FILE *f = fopen("/tmp/foof", "r"); // no-crash + if (!f) return; + fclose(f); +} >From 7453968ac1764adbc70f867d43fa3d63473b09f3 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:39:03 +0200 Subject: [PATCH 2/7] NFC Fixup previous PR comment Addresses: https://github.com/llvm/llvm-project/pull/100085#discussion_r1688051166 --- clang/test/Analysis/stream.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c index 575b32d97be31..aff884f190c8e 100644 --- a/clang/test/Analysis/stream.c +++ b/clang/test/Analysis/stream.c @@ -499,14 +499,14 @@ void gh_93408_regression_ZeroSized(struct ZeroSized *buffer) { fclose(f); } -extern FILE *stdout_like_ptr; -void no_aliasing(void) { +extern FILE *non_standard_stream_ptr; +void test_fopen_does_not_alias_with_standard_streams(void) { FILE *f = fopen("file", "r"); if (!f) return; clang_analyzer_eval(f == stdin); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stdout); // expected-warning {{FALSE}} no-TRUE clang_analyzer_eval(f == stderr); // expected-warning {{FALSE}} no-TRUE - clang_analyzer_eval(f == stdout_like_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} + clang_analyzer_eval(f == non_standard_stream_ptr); // expected-warning {{FALSE}} expected-warning {{TRUE}} if (f != stdout) { fclose(f); } >From db92245ab09f195cbb859d85f2b93a81fd1b2617 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Mon, 29 Jul 2024 10:46:16 +0200 Subject: [PATCH 3/7] NFC Fixup previous PR comment Addresses https://github.com/llvm/llvm-project/pull/100085#discussion_r1688054004 --- .../StaticAnalyzer/Checkers/StreamChecker.cpp | 25 ++- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 942e7541a83cd..4454f30630e27 100644 --- a/clang/li
[clang] [analyzer] Fix crash of StreamChecker when eval calling 'fopen' (PR #100990)
steakhal wrote: > This looks good now, documentation could be a bit more exact in that > operations on standard streams are not checked by the checker, like any other > operation on streams that are not opened on the analysis path. Elaborated the docs section. https://github.com/llvm/llvm-project/pull/100990 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema][ObjC] Add warning options to detect bad name prefixes. (PR #97597)
al45tair wrote: Failure doesn't look like anything to do with this PR. https://github.com/llvm/llvm-project/pull/97597 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix hasName matcher assertion with inline namespaces (PR #100975)
https://github.com/AaronBallman commented: I can't get the assertion to reproduce, but I can see the behavioral change with the first matcher: https://godbolt.org/z/TcsYPoGEh So this should probably come with a release note for the fix? https://github.com/llvm/llvm-project/pull/100975 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AMDGPU] Use the AMDGPUToolChain when targeting C/C++ directly (PR #99687)
https://github.com/jhuber6 updated https://github.com/llvm/llvm-project/pull/99687 >From 59901100a2c11d37947938dfb9db5dd1164cbbf5 Mon Sep 17 00:00:00 2001 From: Joseph Huber Date: Fri, 19 Jul 2024 14:07:18 -0500 Subject: [PATCH 1/3] [AMDGPU] Use the AMDGPUToolChain when targeting C/C++ directly Summary: The `getToolChain` pass uses the triple to determine which toolchain to create. Currently the `amdgcn-amd-amdhsa` triple maps to the `ROCmToolChain` which uses things expected to be provided by `ROCm`. This is neded for OpenCL, but directly targeting C++ does not want this since it's primarily being used for creating GPU runtime code. As far as I know I'm the only user of this, so this shouldn't change anything. Unfortunately, there's no good logic for detercting this, so I simply checked ahead of time if the input is either `foo.cl` or `-x cl foo.c` to choose between the two. This allows us to use the AMDGPU target normally, as otherwise it will error without passing `-nogpulib`. --- clang/lib/Driver/Driver.cpp | 17 +++-- clang/test/Driver/amdgpu-toolchain.c | 3 +++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 8e44d5afa40e0..8e28097dbf1a1 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -6404,9 +6404,22 @@ const ToolChain &Driver::getToolChain(const ArgList &Args, case llvm::Triple::CUDA: TC = std::make_unique(*this, Target, Args); break; -case llvm::Triple::AMDHSA: - TC = std::make_unique(*this, Target, Args); +case llvm::Triple::AMDHSA: { + bool IsOpenCL = + Target.getEnvironment() == llvm::Triple::EnvironmentType::OpenCL || + llvm::any_of(Args.filtered(options::OPT_INPUT, options::OPT_x), + [](auto &Arg) { + if (Arg->getOption().matches(options::OPT_INPUT)) + return StringRef(Arg->getValue()).ends_with(".cl"); + return StringRef(Arg->getValue()).ends_with("cl"); + }); + TC = + IsOpenCL + ? std::make_unique(*this, Target, Args) + : std::make_unique(*this, Target, + Args); break; +} case llvm::Triple::AMDPAL: case llvm::Triple::Mesa3D: TC = std::make_unique(*this, Target, Args); diff --git a/clang/test/Driver/amdgpu-toolchain.c b/clang/test/Driver/amdgpu-toolchain.c index 8ab6a07131474..d12f4fe903f87 100644 --- a/clang/test/Driver/amdgpu-toolchain.c +++ b/clang/test/Driver/amdgpu-toolchain.c @@ -28,3 +28,6 @@ // RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 -nogpulib \ // RUN: -fuse-ld=ld %s 2>&1 | FileCheck -check-prefixes=LD %s // LD: ld.lld + +// RUN: %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx906 %s 2>&1 | FileCheck -check-prefix=ROCM %s +// ROCM-NOT: -mlink-builtin-bitcode >From 51a4697f60d0d42404f0ee9405d25e1c24b43208 Mon Sep 17 00:00:00 2001 From: Joseph Huber Date: Fri, 19 Jul 2024 15:33:41 -0500 Subject: [PATCH 2/3] Refactor to use inputlist --- clang/include/clang/Driver/Driver.h | 7 ++-- clang/lib/Driver/Driver.cpp | 63 + 2 files changed, 41 insertions(+), 29 deletions(-) diff --git a/clang/include/clang/Driver/Driver.h b/clang/include/clang/Driver/Driver.h index 04b46782467d6..e2c713a12567e 100644 --- a/clang/include/clang/Driver/Driver.h +++ b/clang/include/clang/Driver/Driver.h @@ -469,11 +469,11 @@ class Driver { /// BuildInputs - Construct the list of inputs and their types from /// the given arguments. /// - /// \param TC - The default host tool chain. + /// \param TT - The target triple. /// \param Args - The input arguments. /// \param Inputs - The list to store the resulting compilation /// inputs onto. - void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, + void BuildInputs(const llvm::Triple &TT, llvm::opt::DerivedArgList &Args, InputList &Inputs) const; /// BuildActions - Construct the list of actions to perform for the @@ -757,7 +757,8 @@ class Driver { /// Will cache ToolChains for the life of the driver object, and create them /// on-demand. const ToolChain &getToolChain(const llvm::opt::ArgList &Args, -const llvm::Triple &Target) const; +const llvm::Triple &Target, +const InputList &Inputs) const; /// @} diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 8e28097dbf1a1..0cd201b2bc444 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -965,7 +965,7 @@ void Driver::CreateOffloadingDeviceToolChains(Compilation &C, TC = DeviceTC.get(); } else - TC = &getToolChain(C.getInputArgs(), TT); + TC = &getToolChain(C.ge
[clang] [Sema] Preserve ContainsUnexpandedParameterPack in TransformLambdaExpr (PR #86265)
@@ -136,6 +155,11 @@ namespace { /// do not contain unexpanded parameter packs. bool TraverseStmt(Stmt *S) { Expr *E = dyn_cast_or_null(S); + + llvm::SaveAndRestore _(InConstraint); + if (CurrentFunction && CurrentFunction->getTrailingRequiresClause() == S) +InConstraint = true; + cor3ntin wrote: Do we have tests for a lambda (potentially constrained?) used in a requires clause of another function? https://github.com/llvm/llvm-project/pull/86265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Preserve ContainsUnexpandedParameterPack in TransformLambdaExpr (PR #86265)
@@ -1673,14 +1690,12 @@ namespace { // RecoveryExpr that wraps the uninstantiated default argument so // that downstream diagnostics are omitted. ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( - UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), - { UninstExpr }, UninstExpr->getType()); + UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr}, + UninstExpr->getType()); cor3ntin wrote: nothing changed here, right? https://github.com/llvm/llvm-project/pull/86265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Preserve ContainsUnexpandedParameterPack in TransformLambdaExpr (PR #86265)
@@ -14037,6 +14037,15 @@ class Sema final : public SemaBase { TemplateArgument Arg, SmallVectorImpl &Unexpanded); + /// Collect the set of unexpanded parameter packs within the given + /// template argument. + /// + /// \param Arg The template argument that will be traversed to find + /// unexpanded parameter packs. + void collectUnexpandedParameterPacksForFoldExprs( + Expr *E, SmallVectorImpl &Unexpanded, + SmallVectorImpl &UnexpandedFromConstraints); + cor3ntin wrote: The comment is wrong, and i don't understand why we need `collectUnexpandedParameterPacks` specifically for fold expressions. - We already should handle fold expressions correctly https://github.com/llvm/llvm-project/pull/86265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Preserve ContainsUnexpandedParameterPack in TransformLambdaExpr (PR #86265)
@@ -170,6 +194,17 @@ namespace { if (D && D->isParameterPack()) return true; + if (D && D->isFunctionOrFunctionTemplate()) { +FunctionDecl *FD; +if (auto *FTD = dyn_cast(D)) + FD = FTD->getTemplatedDecl(); +else + FD = cast(D); cor3ntin wrote: Do we not have functions to do that somewhere? I feel like i see that sort of pattern all over https://github.com/llvm/llvm-project/pull/86265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Preserve ContainsUnexpandedParameterPack in TransformLambdaExpr (PR #86265)
@@ -4006,6 +4007,37 @@ class TreeTransform { NumExpansions); } + void RebuildLambdaExprImpl(SourceLocation StartLoc, SourceLocation EndLoc, + LambdaScopeInfo *LSI) {} + + ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, + LambdaScopeInfo *LSI) { +CXXRecordDecl *Class = LSI->Lambda; +CXXMethodDecl *CallOperator = LSI->CallOperator; +CallOperator->setLexicalDeclContext(Class); +Decl *TemplateOrNonTemplateCallOperatorDecl = +CallOperator->getDescribedFunctionTemplate() +? CallOperator->getDescribedFunctionTemplate() +: cast(CallOperator); +// FIXME: Is this really the best choice? Keeping the lexical decl context +// set as CurContext seems more faithful to the source. +TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); + +getDerived().RebuildLambdaExprImpl(StartLoc, EndLoc, LSI); cor3ntin wrote: We don't seem to do anything interesting there https://github.com/llvm/llvm-project/pull/86265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Preserve ContainsUnexpandedParameterPack in TransformLambdaExpr (PR #86265)
@@ -4006,6 +4007,37 @@ class TreeTransform { NumExpansions); } + void RebuildLambdaExprImpl(SourceLocation StartLoc, SourceLocation EndLoc, + LambdaScopeInfo *LSI) {} + + ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, + LambdaScopeInfo *LSI) { +CXXRecordDecl *Class = LSI->Lambda; +CXXMethodDecl *CallOperator = LSI->CallOperator; +CallOperator->setLexicalDeclContext(Class); +Decl *TemplateOrNonTemplateCallOperatorDecl = +CallOperator->getDescribedFunctionTemplate() +? CallOperator->getDescribedFunctionTemplate() +: cast(CallOperator); +// FIXME: Is this really the best choice? Keeping the lexical decl context +// set as CurContext seems more faithful to the source. +TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); cor3ntin wrote: Why not just calling BuildLambdaExpr first? https://github.com/llvm/llvm-project/pull/86265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [APINotes] Do not crash for C++ operators (PR #101001)
https://github.com/egorzhdan created https://github.com/llvm/llvm-project/pull/101001 This fixes a crash during `CXXMethod->getName()` in `Sema::ProcessAPINotes`: we were trying to get the name of a C++ method as a string, which fails with an assertion if the name is not a simple identifier. >From 0993d9e4b1161b3ec38309f2b1f00d61da034006 Mon Sep 17 00:00:00 2001 From: Egor Zhdan Date: Mon, 29 Jul 2024 13:01:18 +0100 Subject: [PATCH] [APINotes] Do not crash for C++ operators This fixes a crash during `CXXMethod->getName()` in `Sema::ProcessAPINotes`: we were trying to get the name of a C++ method as a string, which fails with an assertion if the name is not a simple identifier. --- clang/lib/Sema/SemaAPINotes.cpp | 12 +++- clang/test/APINotes/Inputs/Headers/Methods.h | 6 ++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/clang/lib/Sema/SemaAPINotes.cpp b/clang/lib/Sema/SemaAPINotes.cpp index be5b7b92dfe6f..2350cbc0f420f 100644 --- a/clang/lib/Sema/SemaAPINotes.cpp +++ b/clang/lib/Sema/SemaAPINotes.cpp @@ -1044,11 +1044,13 @@ void Sema::ProcessAPINotes(Decl *D) { if (auto TagContext = dyn_cast(D->getDeclContext())) { if (auto CXXMethod = dyn_cast(D)) { - for (auto Reader : APINotes.findAPINotes(D->getLocation())) { -if (auto Context = UnwindTagContext(TagContext, APINotes)) { - auto Info = - Reader->lookupCXXMethod(Context->id, CXXMethod->getName()); - ProcessVersionedAPINotes(*this, CXXMethod, Info); + if (CXXMethod->getIdentifier()) { +for (auto Reader : APINotes.findAPINotes(D->getLocation())) { + if (auto Context = UnwindTagContext(TagContext, APINotes)) { +auto Info = +Reader->lookupCXXMethod(Context->id, CXXMethod->getName()); +ProcessVersionedAPINotes(*this, CXXMethod, Info); + } } } } diff --git a/clang/test/APINotes/Inputs/Headers/Methods.h b/clang/test/APINotes/Inputs/Headers/Methods.h index 6a96b12762871..cbb57ccd0afbd 100644 --- a/clang/test/APINotes/Inputs/Headers/Methods.h +++ b/clang/test/APINotes/Inputs/Headers/Methods.h @@ -2,6 +2,8 @@ struct IntWrapper { int value; IntWrapper getIncremented() const { return {value + 1}; } + + IntWrapper operator+(const IntWrapper& RHS) const { return {value + RHS.value}; } }; struct Outer { @@ -9,5 +11,9 @@ struct Outer { int value; Inner getDecremented() const { return {value - 1}; } + +bool operator==(const Inner& RHS) const { + return value == RHS.value; +} }; }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [APINotes] Do not crash for C++ operators (PR #101001)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Egor Zhdan (egorzhdan) Changes This fixes a crash during `CXXMethod->getName()` in `Sema::ProcessAPINotes`: we were trying to get the name of a C++ method as a string, which fails with an assertion if the name is not a simple identifier. --- Full diff: https://github.com/llvm/llvm-project/pull/101001.diff 2 Files Affected: - (modified) clang/lib/Sema/SemaAPINotes.cpp (+7-5) - (modified) clang/test/APINotes/Inputs/Headers/Methods.h (+6) ``diff diff --git a/clang/lib/Sema/SemaAPINotes.cpp b/clang/lib/Sema/SemaAPINotes.cpp index be5b7b92dfe6f..2350cbc0f420f 100644 --- a/clang/lib/Sema/SemaAPINotes.cpp +++ b/clang/lib/Sema/SemaAPINotes.cpp @@ -1044,11 +1044,13 @@ void Sema::ProcessAPINotes(Decl *D) { if (auto TagContext = dyn_cast(D->getDeclContext())) { if (auto CXXMethod = dyn_cast(D)) { - for (auto Reader : APINotes.findAPINotes(D->getLocation())) { -if (auto Context = UnwindTagContext(TagContext, APINotes)) { - auto Info = - Reader->lookupCXXMethod(Context->id, CXXMethod->getName()); - ProcessVersionedAPINotes(*this, CXXMethod, Info); + if (CXXMethod->getIdentifier()) { +for (auto Reader : APINotes.findAPINotes(D->getLocation())) { + if (auto Context = UnwindTagContext(TagContext, APINotes)) { +auto Info = +Reader->lookupCXXMethod(Context->id, CXXMethod->getName()); +ProcessVersionedAPINotes(*this, CXXMethod, Info); + } } } } diff --git a/clang/test/APINotes/Inputs/Headers/Methods.h b/clang/test/APINotes/Inputs/Headers/Methods.h index 6a96b12762871..cbb57ccd0afbd 100644 --- a/clang/test/APINotes/Inputs/Headers/Methods.h +++ b/clang/test/APINotes/Inputs/Headers/Methods.h @@ -2,6 +2,8 @@ struct IntWrapper { int value; IntWrapper getIncremented() const { return {value + 1}; } + + IntWrapper operator+(const IntWrapper& RHS) const { return {value + RHS.value}; } }; struct Outer { @@ -9,5 +11,9 @@ struct Outer { int value; Inner getDecremented() const { return {value - 1}; } + +bool operator==(const Inner& RHS) const { + return value == RHS.value; +} }; }; `` https://github.com/llvm/llvm-project/pull/101001 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits