[clang] [llvm] [clang] Use separator for large numeric values in overflow diagnostic (PR #80939)
https://github.com/Atousa updated https://github.com/llvm/llvm-project/pull/80939 >From ac75fc2873fc7b8eec6c24ba97f4673e94457c8e Mon Sep 17 00:00:00 2001 From: Atousa Duprat Date: Tue, 6 Feb 2024 21:02:05 -0800 Subject: [PATCH 1/5] [clang] Use separator for large numeric values in overflow diagnostic Add functionality to APInt::toString() that allows it to insert separators between groups of digits, using the C++ litteral separator ' between groups. Fixes issue #58228 --- clang/lib/AST/ExprConstant.cpp | 6 +- clang/test/AST/Interp/c.c | 4 +- clang/test/C/drs/dr0xx.c| 2 +- clang/test/C/drs/dr2xx.c| 2 +- clang/test/Sema/integer-overflow.c | 100 - clang/test/Sema/switch-1.c | 6 +- clang/test/SemaCXX/enum.cpp | 4 +- clang/test/SemaCXX/integer-overflow.cpp | 112 ++-- clang/test/SemaObjC/integer-overflow.m | 4 +- clang/test/SemaObjC/objc-literal-nsnumber.m | 2 +- llvm/include/llvm/ADT/APInt.h | 3 +- llvm/include/llvm/ADT/StringExtras.h| 5 +- llvm/lib/Support/APInt.cpp | 24 - llvm/unittests/ADT/APIntTest.cpp| 35 ++ 14 files changed, 185 insertions(+), 124 deletions(-) diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 089bc2094567f7..d9037072c6767f 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -2774,7 +2774,8 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_integer_constant_overflow) - << toString(Result, 10) << E->getType() << E->getSourceRange(); + << toString(Result, 10, Result.isSigned(), false, true, true) + << E->getType() << E->getSourceRange(); return HandleOverflow(Info, E, Value, E->getType()); } return true; @@ -13852,7 +13853,8 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_integer_constant_overflow) -<< toString(Value, 10) << E->getType() << E->getSourceRange(); +<< toString(Value, 10, Value.isSigned(), false, true, true) +<< E->getType() << E->getSourceRange(); if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), E->getType())) diff --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c index 9ab271a82aeef9..aa067b0bc74831 100644 --- a/clang/test/AST/Interp/c.c +++ b/clang/test/AST/Interp/c.c @@ -109,9 +109,9 @@ int somefunc(int i) { // pedantic-expected-warning {{left operand of comma operator has no effect}} \ // pedantic-expected-warning {{overflow in expression; result is 131073}} \ // ref-warning {{left operand of comma operator has no effect}} \ - // ref-warning {{overflow in expression; result is 131073}} \ + // ref-warning {{overflow in expression; result is 131'073}} \ // pedantic-ref-warning {{left operand of comma operator has no effect}} \ - // pedantic-ref-warning {{overflow in expression; result is 131073}} + // pedantic-ref-warning {{overflow in expression; result is 131'073}} } diff --git a/clang/test/C/drs/dr0xx.c b/clang/test/C/drs/dr0xx.c index d9c1fbe4ee40ab..c93cfb63d604cf 100644 --- a/clang/test/C/drs/dr0xx.c +++ b/clang/test/C/drs/dr0xx.c @@ -214,7 +214,7 @@ _Static_assert(__builtin_types_compatible_p(struct S { int a; }, union U { int a */ void dr031(int i) { switch (i) { - case __INT_MAX__ + 1: break; /* expected-warning {{overflow in expression; result is -2147483648 with type 'int'}} */ + case __INT_MAX__ + 1: break; /* expected-warning {{overflow in expression; result is -2'147'483'648 with type 'int'}} */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch" /* Silence the targets which issue: diff --git a/clang/test/C/drs/dr2xx.c b/clang/test/C/drs/dr2xx.c index 9c8d77518ab55e..1b68b65acca6af 100644 --- a/clang/test/C/drs/dr2xx.c +++ b/clang/test/C/drs/dr2xx.c @@ -277,7 +277,7 @@ void dr258(void) { void dr261(void) { /* This is still an integer constant expression despite the overflow. */ enum e1 { -ex1 = __INT_MAX__ + 1 /* expected-warning {{overflow in expression; result is -2147483648 with type 'int'}} */ +ex1 = __INT_MAX__ + 1 /* expected-warning {{overflow in expression; result is -2'147'483'648 with type 'int'}} */ }; /* This is not an integer constant ex
[clang] [llvm] [openmp] [PGO][OpenMP] Instrumentation for GPU devices (PR #76587)
https://github.com/EthanLuisMcDonough updated https://github.com/llvm/llvm-project/pull/76587 >From 530eb982b9770190377bb0bd09c5cb715f34d484 Mon Sep 17 00:00:00 2001 From: Ethan Luis McDonough Date: Fri, 15 Dec 2023 20:38:38 -0600 Subject: [PATCH 01/14] Add profiling functions to libomptarget --- .../include/llvm/Frontend/OpenMP/OMPKinds.def | 3 +++ openmp/libomptarget/DeviceRTL/CMakeLists.txt | 2 ++ .../DeviceRTL/include/Profiling.h | 21 +++ .../libomptarget/DeviceRTL/src/Profiling.cpp | 19 + 4 files changed, 45 insertions(+) create mode 100644 openmp/libomptarget/DeviceRTL/include/Profiling.h create mode 100644 openmp/libomptarget/DeviceRTL/src/Profiling.cpp diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def b/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def index d22d2a8e948b00..1d887d5cb58127 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def +++ b/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def @@ -503,6 +503,9 @@ __OMP_RTL(__kmpc_barrier_simple_generic, false, Void, IdentPtr, Int32) __OMP_RTL(__kmpc_warp_active_thread_mask, false, Int64,) __OMP_RTL(__kmpc_syncwarp, false, Void, Int64) +__OMP_RTL(__llvm_profile_register_function, false, Void, VoidPtr) +__OMP_RTL(__llvm_profile_register_names_function, false, Void, VoidPtr, Int64) + __OMP_RTL(__last, false, Void, ) #undef __OMP_RTL diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt b/openmp/libomptarget/DeviceRTL/CMakeLists.txt index 1ce3e1e40a80ab..55ee15d068c67b 100644 --- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt +++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt @@ -89,6 +89,7 @@ set(include_files ${include_directory}/Interface.h ${include_directory}/LibC.h ${include_directory}/Mapping.h + ${include_directory}/Profiling.h ${include_directory}/State.h ${include_directory}/Synchronization.h ${include_directory}/Types.h @@ -104,6 +105,7 @@ set(src_files ${source_directory}/Mapping.cpp ${source_directory}/Misc.cpp ${source_directory}/Parallelism.cpp + ${source_directory}/Profiling.cpp ${source_directory}/Reduction.cpp ${source_directory}/State.cpp ${source_directory}/Synchronization.cpp diff --git a/openmp/libomptarget/DeviceRTL/include/Profiling.h b/openmp/libomptarget/DeviceRTL/include/Profiling.h new file mode 100644 index 00..68c7744cd60752 --- /dev/null +++ b/openmp/libomptarget/DeviceRTL/include/Profiling.h @@ -0,0 +1,21 @@ +//=== Profiling.h - OpenMP interface -- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +// +// +//===--===// + +#ifndef OMPTARGET_DEVICERTL_PROFILING_H +#define OMPTARGET_DEVICERTL_PROFILING_H + +extern "C" { + +void __llvm_profile_register_function(void *ptr); +void __llvm_profile_register_names_function(void *ptr, long int i); +} + +#endif diff --git a/openmp/libomptarget/DeviceRTL/src/Profiling.cpp b/openmp/libomptarget/DeviceRTL/src/Profiling.cpp new file mode 100644 index 00..799477f5e47d27 --- /dev/null +++ b/openmp/libomptarget/DeviceRTL/src/Profiling.cpp @@ -0,0 +1,19 @@ +//===--- Profiling.cpp C++ ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "Profiling.h" + +#pragma omp begin declare target device_type(nohost) + +extern "C" { + +void __llvm_profile_register_function(void *ptr) {} +void __llvm_profile_register_names_function(void *ptr, long int i) {} +} + +#pragma omp end declare target >From fb067d4ffe604fd68cf90b705db1942bce49dbb1 Mon Sep 17 00:00:00 2001 From: Ethan Luis McDonough Date: Sat, 16 Dec 2023 01:18:41 -0600 Subject: [PATCH 02/14] Fix PGO instrumentation for GPU targets --- clang/lib/CodeGen/CodeGenPGO.cpp | 10 -- .../lib/Transforms/Instrumentation/InstrProfiling.cpp | 11 --- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/clang/lib/CodeGen/CodeGenPGO.cpp b/clang/lib/CodeGen/CodeGenPGO.cpp index 81bf8ea696b164..edae6885b528ac 100644 --- a/clang/lib/CodeGen/CodeGenPGO.cpp +++ b/clang/lib/CodeGen/CodeGenPGO.cpp @@ -959,8 +959,14 @@ void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S, unsigned Counter = (*RegionCounterMap)[S]; - llvm::Value *Args[] = {FuncNameVar, - Builder.getInt64(FunctionHash), + // Make sure that pointer to global is passed in with zero addrspace + //
[clang] [clang][analyzer] Reformat code of BoolAssignmentChecker (NFC). (PR #81461)
https://github.com/balazske closed https://github.com/llvm/llvm-project/pull/81461 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] a2eb234 - [clang][analyzer] Reformat code of BoolAssignmentChecker (NFC). (#81461)
Author: Balázs Kéri Date: 2024-02-14T08:38:24+01:00 New Revision: a2eb2340963c905b21ad3a2eda2688e3cd80192d URL: https://github.com/llvm/llvm-project/commit/a2eb2340963c905b21ad3a2eda2688e3cd80192d DIFF: https://github.com/llvm/llvm-project/commit/a2eb2340963c905b21ad3a2eda2688e3cd80192d.diff LOG: [clang][analyzer] Reformat code of BoolAssignmentChecker (NFC). (#81461) This is only a code reformatting and rename of variables to the newer format. Added: Modified: clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp Removed: diff --git a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp index a09db6d2d0ec5b..837cbbce8f45f3 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp @@ -23,19 +23,19 @@ using namespace clang; using namespace ento; namespace { - class BoolAssignmentChecker : public Checker< check::Bind > { -const BugType BT{this, "Assignment of a non-Boolean value"}; -void emitReport(ProgramStateRef state, CheckerContext &C, -bool IsTainted = false) const; - - public: -void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const; - }; +class BoolAssignmentChecker : public Checker { + const BugType BT{this, "Assignment of a non-Boolean value"}; + void emitReport(ProgramStateRef State, CheckerContext &C, + bool IsTainted = false) const; + +public: + void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const; +}; } // end anonymous namespace -void BoolAssignmentChecker::emitReport(ProgramStateRef state, CheckerContext &C, +void BoolAssignmentChecker::emitReport(ProgramStateRef State, CheckerContext &C, bool IsTainted) const { - if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) { + if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) { StringRef Msg = IsTainted ? "Might assign a tainted non-Boolean value" : "Assignment of a non-Boolean value"; C.emitReport(std::make_unique(BT, Msg, N)); @@ -47,59 +47,58 @@ static bool isBooleanType(QualType Ty) { return true; if (const TypedefType *TT = Ty->getAs()) -return TT->getDecl()->getName() == "BOOL" || // Objective-C - TT->getDecl()->getName() == "_Bool" || // stdbool.h < C99 - TT->getDecl()->getName() == "Boolean"; // MacTypes.h +return TT->getDecl()->getName() == "BOOL" || // Objective-C + TT->getDecl()->getName() == "_Bool" || // stdbool.h < C99 + TT->getDecl()->getName() == "Boolean"; // MacTypes.h return false; } -void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, +void BoolAssignmentChecker::checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const { // We are only interested in stores into Booleans. const TypedValueRegion *TR = -dyn_cast_or_null(loc.getAsRegion()); + dyn_cast_or_null(Loc.getAsRegion()); if (!TR) return; - QualType valTy = TR->getValueType(); + QualType RegTy = TR->getValueType(); - if (!isBooleanType(valTy)) + if (!isBooleanType(RegTy)) return; // Get the value of the right-hand side. We only care about values // that are defined (UnknownVals and UndefinedVals are handled by other // checkers). - std::optional NV = val.getAs(); + std::optional NV = Val.getAs(); if (!NV) return; // Check if the assigned value meets our criteria for correctness. It must // be a value that is either 0 or 1. One way to check this is to see if // the value is possibly < 0 (for a negative value) or greater than 1. - ProgramStateRef state = C.getState(); - SValBuilder &svalBuilder = C.getSValBuilder(); - BasicValueFactory &BVF = svalBuilder.getBasicValueFactory(); + ProgramStateRef State = C.getState(); + BasicValueFactory &BVF = C.getSValBuilder().getBasicValueFactory(); ConstraintManager &CM = C.getConstraintManager(); - llvm::APSInt Zero = BVF.getValue(0, valTy); - llvm::APSInt One = BVF.getValue(1, valTy); + llvm::APSInt Zero = BVF.getValue(0, RegTy); + llvm::APSInt One = BVF.getValue(1, RegTy); ProgramStateRef StIn, StOut; - std::tie(StIn, StOut) = CM.assumeInclusiveRangeDual(state, *NV, Zero, One); + std::tie(StIn, StOut) = CM.assumeInclusiveRangeDual(State, *NV, Zero, One); if (!StIn) emitReport(StOut, C); - if (StIn && StOut && taint::isTainted(state, *NV)) + if (StIn && StOut && taint::isTainted(State, *NV)) emitReport(StOut, C, /*IsTainted=*/true); } -void ento::registerBoolAssignmentChecker(CheckerManager &mgr) { -mgr.registerChecker(); +void ento::registerBoolAssignmentChecker(CheckerManager &Mgr) { + Mgr.registerChecker(); } -bool
[clang] [clang-format][NFC] Drop "Always" in "AlwaysBreakAfterReturnType". (PR #81591)
@@ -1130,14 +1129,13 @@ template <> struct MappingTraits { // AlwaysBreakAfterReturnType was not, initialize the latter from the // former for backwards compatibility. owenca wrote: ```suggestion // BreakAfterReturnType was not, initialize the latter from the former for // backwards compatibility. ``` https://github.com/llvm/llvm-project/pull/81591 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format][NFC] Drop "Always" in "AlwaysBreakAfterReturnType". (PR #81591)
@@ -1871,10 +1869,10 @@ FormatStyle getWebKitStyle() { FormatStyle getGNUStyle() { FormatStyle Style = getLLVMStyle(); Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; - Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; Style.BreakBeforeBraces = FormatStyle::BS_GNU; Style.BreakBeforeTernaryOperators = true; + Style.BreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; owenca wrote: Not sorted. https://github.com/llvm/llvm-project/pull/81591 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [dataflow] Fix crash when InitListExpr is not a prvalue (PR #80970)
https://github.com/martinboehme approved this pull request. https://github.com/llvm/llvm-project/pull/80970 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][CodeGen] Loose the cast check when emitting builtins (PR #81669)
arsenm wrote: > Sorry, I should have clearly mentioned that. Yes, it is for my followup > change #80908. In #80908, we changed the type of LLVM builtin but kept the > corresponding clang builtin unchanged to avoid breaking existing uses. Don't see how that could be related; you can losslessly bitconvert between i16 and bfloat https://github.com/llvm/llvm-project/pull/81669 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Always add a space after #if and #elif (PR #81578)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/81578 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] eafe98f - [clang-format] Always add a space after #if and #elif (#81578)
Author: Owen Pan Date: 2024-02-13T22:35:52-08:00 New Revision: eafe98f937c790632452d1ab741477e4fb7e5531 URL: https://github.com/llvm/llvm-project/commit/eafe98f937c790632452d1ab741477e4fb7e5531 DIFF: https://github.com/llvm/llvm-project/commit/eafe98f937c790632452d1ab741477e4fb7e5531.diff LOG: [clang-format] Always add a space after #if and #elif (#81578) Fixes #81569. Added: Modified: clang/lib/Format/TokenAnnotator.cpp clang/unittests/Format/FormatTest.cpp Removed: diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index b9a000faae7cf7..08a49bc17f13f3 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1856,6 +1856,8 @@ class AnnotatingParser { case tok::pp_elif: Contexts.back().IsExpression = true; next(); + if (CurrentToken) +CurrentToken->SpacesRequiredBefore = true; parseLine(); break; default: diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 13937a15fdaee2..79cd521b6a9998 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -16491,6 +16491,10 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { verifyFormat("T A::operator()();", NoSpace); verifyFormat("X A::operator++(T);", NoSpace); verifyFormat("auto lambda = []() { return 0; };", NoSpace); + verifyFormat("#if (foo || bar) && baz\n" + "#elif ((a || b) && c) || d\n" + "#endif", + NoSpace); FormatStyle Space = getLLVMStyle(); Space.SpaceBeforeParens = FormatStyle::SBPO_Always; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add comments and macros support to Python bindings (PR #81684)
https://github.com/dnmiller updated https://github.com/llvm/llvm-project/pull/81684 >From 0617712f89ef0193f6112680e25bd7b40002d6fd Mon Sep 17 00:00:00 2001 From: "Daniel N. Miller (APD)" Date: Tue, 13 Feb 2024 15:12:05 -0800 Subject: [PATCH] Add comments and macros support to Python bindings --- clang/bindings/python/clang/cindex.py | 349 ++ 1 file changed, 349 insertions(+) diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 44a34ca196274c..49b4a1f3a765a1 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -1378,6 +1378,7 @@ def __repr__(self): # A code completion overload candidate. CursorKind.OVERLOAD_CANDIDATE = CursorKind(700) + ### Template Argument Kinds ### class TemplateArgumentKind(BaseEnumeration): """ @@ -1396,6 +1397,7 @@ class TemplateArgumentKind(BaseEnumeration): TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3) TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4) + ### Exception Specification Kinds ### class ExceptionSpecificationKind(BaseEnumeration): """ @@ -1907,6 +1909,11 @@ def raw_comment(self): """Returns the raw comment text associated with that Cursor""" return conf.lib.clang_Cursor_getRawCommentText(self) +@property +def parsed_comment(self): +"""Returns the parsed comment text associaetd with that Cursor""" +return conf.lib.clang_Cursor_getParsedComment(self) + def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) @@ -1994,6 +2001,18 @@ def get_bitfield_width(self): """ return conf.lib.clang_getFieldDeclBitWidth(self) +def is_macro_function(self): +""" +Check if the field is a macro function. +""" +return conf.lib.clang_Cursor_isMacroFunctionLike(self) + +def is_macro_builtin(self): +""" +Check if the field is a macro function. +""" +return conf.lib.clang_Cursor_isMacroBuiltin(self) + @staticmethod def from_result(res, fn, args): assert isinstance(res, Cursor) @@ -2243,6 +2262,74 @@ def __repr__(self): TypeKind.EXTVECTOR = TypeKind(176) TypeKind.ATOMIC = TypeKind(177) +### Comment Kinds ### + + +class CommentKind(BaseEnumeration): +""" +Describes the kind of comment. +""" + +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return "CommentKind.%s" % (self.name,) + + +CommentKind.NULL = CommentKind(0) +CommentKind.TEXT = CommentKind(1) +CommentKind.INLINECOMMAND = CommentKind(2) +CommentKind.HTMLSTARTTAG = CommentKind(3) +CommentKind.HTMLENDTAG = CommentKind(4) +CommentKind.PARAGRAPH = CommentKind(5) +CommentKind.BLOCKCOMMAND = CommentKind(6) +CommentKind.PARAMCOMMAND = CommentKind(7) +CommentKind.TPARAMCOMMAND = CommentKind(8) +CommentKind.VERBATIMBLOCKCOMMAND = CommentKind(9) +CommentKind.VERBATIMBLOCKLINE = CommentKind(10) +CommentKind.VERBATIMLINE = CommentKind(11) +CommentKind.FULLCOMMENT = CommentKind(12) + + +class CommentInlineCommandRenderKind(BaseEnumeration): +""" +Describes the kind of rendering mode of an inline command. +""" + +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return "CommentInlineCommandRenderKind.%s" % (self.name,) + + +CommentInlineCommandRenderKind.NORMAL = CommentInlineCommandRenderKind(0) +CommentInlineCommandRenderKind.BOLD = CommentInlineCommandRenderKind(1) +CommentInlineCommandRenderKind.MONOSPACED = CommentInlineCommandRenderKind(2) +CommentInlineCommandRenderKind.EMPHASIZE = CommentInlineCommandRenderKind(3) + + +class CommentParamPassDirection(BaseEnumeration): +""" +Describes the kind of parameter passing direction for \\param +or \\arg command +""" + +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return "CommentParamPassDirection.%s" % (self.name,) + + +CommentParamPassDirection.IN = CommentParamPassDirection(0) +CommentParamPassDirection.OUT = CommentParamPassDirection(1) +CommentParamPassDirection.INOU = CommentParamPassDirection(2) + class RefQualifierKind(BaseEnumeration): """Describes a specific ref-qualifier of a type.""" @@ -3574,6 +3661,187 @@ def write_main_file_to_stdout(self): callbacks["cursor_visit"] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) callbacks["fields_visit"] = CFUNCTYPE(c_int, Cursor, py_object) + +class CXTranslationUnitImpl(Structure): +pass # opaque structure + + +CXTranslationUnit = POINTER(CXTranslationUnitImpl) + + +class Comment(Structure): +_fields_ = [("ASTNode", c_void_p), ("TranslationUnit", CXTranslationUnit)] + +def get_text(self): +return conf.lib.clang_TextComment_getText(self) + +@p
[clang] [llvm] [clang] Use separator for large numeric values in overflow diagnostic (PR #80939)
https://github.com/Atousa updated https://github.com/llvm/llvm-project/pull/80939 >From ac75fc2873fc7b8eec6c24ba97f4673e94457c8e Mon Sep 17 00:00:00 2001 From: Atousa Duprat Date: Tue, 6 Feb 2024 21:02:05 -0800 Subject: [PATCH 1/5] [clang] Use separator for large numeric values in overflow diagnostic Add functionality to APInt::toString() that allows it to insert separators between groups of digits, using the C++ litteral separator ' between groups. Fixes issue #58228 --- clang/lib/AST/ExprConstant.cpp | 6 +- clang/test/AST/Interp/c.c | 4 +- clang/test/C/drs/dr0xx.c| 2 +- clang/test/C/drs/dr2xx.c| 2 +- clang/test/Sema/integer-overflow.c | 100 - clang/test/Sema/switch-1.c | 6 +- clang/test/SemaCXX/enum.cpp | 4 +- clang/test/SemaCXX/integer-overflow.cpp | 112 ++-- clang/test/SemaObjC/integer-overflow.m | 4 +- clang/test/SemaObjC/objc-literal-nsnumber.m | 2 +- llvm/include/llvm/ADT/APInt.h | 3 +- llvm/include/llvm/ADT/StringExtras.h| 5 +- llvm/lib/Support/APInt.cpp | 24 - llvm/unittests/ADT/APIntTest.cpp| 35 ++ 14 files changed, 185 insertions(+), 124 deletions(-) diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 089bc2094567f7..d9037072c6767f 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -2774,7 +2774,8 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_integer_constant_overflow) - << toString(Result, 10) << E->getType() << E->getSourceRange(); + << toString(Result, 10, Result.isSigned(), false, true, true) + << E->getType() << E->getSourceRange(); return HandleOverflow(Info, E, Value, E->getType()); } return true; @@ -13852,7 +13853,8 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_integer_constant_overflow) -<< toString(Value, 10) << E->getType() << E->getSourceRange(); +<< toString(Value, 10, Value.isSigned(), false, true, true) +<< E->getType() << E->getSourceRange(); if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), E->getType())) diff --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c index 9ab271a82aeef9..aa067b0bc74831 100644 --- a/clang/test/AST/Interp/c.c +++ b/clang/test/AST/Interp/c.c @@ -109,9 +109,9 @@ int somefunc(int i) { // pedantic-expected-warning {{left operand of comma operator has no effect}} \ // pedantic-expected-warning {{overflow in expression; result is 131073}} \ // ref-warning {{left operand of comma operator has no effect}} \ - // ref-warning {{overflow in expression; result is 131073}} \ + // ref-warning {{overflow in expression; result is 131'073}} \ // pedantic-ref-warning {{left operand of comma operator has no effect}} \ - // pedantic-ref-warning {{overflow in expression; result is 131073}} + // pedantic-ref-warning {{overflow in expression; result is 131'073}} } diff --git a/clang/test/C/drs/dr0xx.c b/clang/test/C/drs/dr0xx.c index d9c1fbe4ee40ab..c93cfb63d604cf 100644 --- a/clang/test/C/drs/dr0xx.c +++ b/clang/test/C/drs/dr0xx.c @@ -214,7 +214,7 @@ _Static_assert(__builtin_types_compatible_p(struct S { int a; }, union U { int a */ void dr031(int i) { switch (i) { - case __INT_MAX__ + 1: break; /* expected-warning {{overflow in expression; result is -2147483648 with type 'int'}} */ + case __INT_MAX__ + 1: break; /* expected-warning {{overflow in expression; result is -2'147'483'648 with type 'int'}} */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch" /* Silence the targets which issue: diff --git a/clang/test/C/drs/dr2xx.c b/clang/test/C/drs/dr2xx.c index 9c8d77518ab55e..1b68b65acca6af 100644 --- a/clang/test/C/drs/dr2xx.c +++ b/clang/test/C/drs/dr2xx.c @@ -277,7 +277,7 @@ void dr258(void) { void dr261(void) { /* This is still an integer constant expression despite the overflow. */ enum e1 { -ex1 = __INT_MAX__ + 1 /* expected-warning {{overflow in expression; result is -2147483648 with type 'int'}} */ +ex1 = __INT_MAX__ + 1 /* expected-warning {{overflow in expression; result is -2'147'483'648 with type 'int'}} */ }; /* This is not an integer constant ex
[clang] [llvm] [clang] Use separator for large numeric values in overflow diagnostic (PR #80939)
https://github.com/Atousa updated https://github.com/llvm/llvm-project/pull/80939 >From ac75fc2873fc7b8eec6c24ba97f4673e94457c8e Mon Sep 17 00:00:00 2001 From: Atousa Duprat Date: Tue, 6 Feb 2024 21:02:05 -0800 Subject: [PATCH 1/5] [clang] Use separator for large numeric values in overflow diagnostic Add functionality to APInt::toString() that allows it to insert separators between groups of digits, using the C++ litteral separator ' between groups. Fixes issue #58228 --- clang/lib/AST/ExprConstant.cpp | 6 +- clang/test/AST/Interp/c.c | 4 +- clang/test/C/drs/dr0xx.c| 2 +- clang/test/C/drs/dr2xx.c| 2 +- clang/test/Sema/integer-overflow.c | 100 - clang/test/Sema/switch-1.c | 6 +- clang/test/SemaCXX/enum.cpp | 4 +- clang/test/SemaCXX/integer-overflow.cpp | 112 ++-- clang/test/SemaObjC/integer-overflow.m | 4 +- clang/test/SemaObjC/objc-literal-nsnumber.m | 2 +- llvm/include/llvm/ADT/APInt.h | 3 +- llvm/include/llvm/ADT/StringExtras.h| 5 +- llvm/lib/Support/APInt.cpp | 24 - llvm/unittests/ADT/APIntTest.cpp| 35 ++ 14 files changed, 185 insertions(+), 124 deletions(-) diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 089bc2094567f7..d9037072c6767f 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -2774,7 +2774,8 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_integer_constant_overflow) - << toString(Result, 10) << E->getType() << E->getSourceRange(); + << toString(Result, 10, Result.isSigned(), false, true, true) + << E->getType() << E->getSourceRange(); return HandleOverflow(Info, E, Value, E->getType()); } return true; @@ -13852,7 +13853,8 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_integer_constant_overflow) -<< toString(Value, 10) << E->getType() << E->getSourceRange(); +<< toString(Value, 10, Value.isSigned(), false, true, true) +<< E->getType() << E->getSourceRange(); if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), E->getType())) diff --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c index 9ab271a82aeef9..aa067b0bc74831 100644 --- a/clang/test/AST/Interp/c.c +++ b/clang/test/AST/Interp/c.c @@ -109,9 +109,9 @@ int somefunc(int i) { // pedantic-expected-warning {{left operand of comma operator has no effect}} \ // pedantic-expected-warning {{overflow in expression; result is 131073}} \ // ref-warning {{left operand of comma operator has no effect}} \ - // ref-warning {{overflow in expression; result is 131073}} \ + // ref-warning {{overflow in expression; result is 131'073}} \ // pedantic-ref-warning {{left operand of comma operator has no effect}} \ - // pedantic-ref-warning {{overflow in expression; result is 131073}} + // pedantic-ref-warning {{overflow in expression; result is 131'073}} } diff --git a/clang/test/C/drs/dr0xx.c b/clang/test/C/drs/dr0xx.c index d9c1fbe4ee40ab..c93cfb63d604cf 100644 --- a/clang/test/C/drs/dr0xx.c +++ b/clang/test/C/drs/dr0xx.c @@ -214,7 +214,7 @@ _Static_assert(__builtin_types_compatible_p(struct S { int a; }, union U { int a */ void dr031(int i) { switch (i) { - case __INT_MAX__ + 1: break; /* expected-warning {{overflow in expression; result is -2147483648 with type 'int'}} */ + case __INT_MAX__ + 1: break; /* expected-warning {{overflow in expression; result is -2'147'483'648 with type 'int'}} */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch" /* Silence the targets which issue: diff --git a/clang/test/C/drs/dr2xx.c b/clang/test/C/drs/dr2xx.c index 9c8d77518ab55e..1b68b65acca6af 100644 --- a/clang/test/C/drs/dr2xx.c +++ b/clang/test/C/drs/dr2xx.c @@ -277,7 +277,7 @@ void dr258(void) { void dr261(void) { /* This is still an integer constant expression despite the overflow. */ enum e1 { -ex1 = __INT_MAX__ + 1 /* expected-warning {{overflow in expression; result is -2147483648 with type 'int'}} */ +ex1 = __INT_MAX__ + 1 /* expected-warning {{overflow in expression; result is -2'147'483'648 with type 'int'}} */ }; /* This is not an integer constant ex
[clang] 61c83e9 - Revert "[clang-format][NFC] Make LangOpts global in namespace Format"
Author: Owen Pan Date: 2024-02-13T21:02:14-08:00 New Revision: 61c83e9491b2be71a54b255cdb11f65365245953 URL: https://github.com/llvm/llvm-project/commit/61c83e9491b2be71a54b255cdb11f65365245953 DIFF: https://github.com/llvm/llvm-project/commit/61c83e9491b2be71a54b255cdb11f65365245953.diff LOG: Revert "[clang-format][NFC] Make LangOpts global in namespace Format" This reverts commit 32e65b0b8a743678974c7ca7913c1d6c41bb0772. It seems to break some PowerPC bots. See https://github.com/llvm/llvm-project/pull/81390#issuecomment-1941964803. Added: Modified: clang/lib/Format/FormatTokenLexer.cpp clang/lib/Format/FormatTokenLexer.h clang/lib/Format/IntegerLiteralSeparatorFixer.cpp clang/lib/Format/TokenAnalyzer.cpp clang/lib/Format/TokenAnalyzer.h Removed: diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp index 492e7e96dd22e6..036f7e6a4efc1e 100644 --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -13,7 +13,11 @@ //===--===// #include "FormatTokenLexer.h" -#include "TokenAnalyzer.h" +#include "FormatToken.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/SourceManager.h" +#include "clang/Format/Format.h" +#include "llvm/Support/Regex.h" namespace clang { namespace format { @@ -24,12 +28,12 @@ FormatTokenLexer::FormatTokenLexer( llvm::SpecificBumpPtrAllocator &Allocator, IdentifierTable &IdentTable) : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}), - Column(Column), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID), + Column(Column), TrailingWhitespace(0), + LangOpts(getFormattingLangOpts(Style)), SourceMgr(SourceMgr), ID(ID), Style(Style), IdentTable(IdentTable), Keywords(IdentTable), Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0), FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin), MacroBlockEndRegex(Style.MacroBlockEnd) { - assert(LangOpts.CPlusPlus); Lex.reset(new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts)); Lex->SetKeepWhitespaceMode(true); @@ -1438,7 +1442,7 @@ void FormatTokenLexer::readRawToken(FormatToken &Tok) { void FormatTokenLexer::resetLexer(unsigned Offset) { StringRef Buffer = SourceMgr.getBufferData(ID); - assert(LangOpts.CPlusPlus); + LangOpts = getFormattingLangOpts(Style); Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts, Buffer.begin(), Buffer.begin() + Offset, Buffer.end())); Lex->SetKeepWhitespaceMode(true); diff --git a/clang/lib/Format/FormatTokenLexer.h b/clang/lib/Format/FormatTokenLexer.h index ca91c5b7d20d4e..65dd733bd53352 100644 --- a/clang/lib/Format/FormatTokenLexer.h +++ b/clang/lib/Format/FormatTokenLexer.h @@ -17,9 +17,14 @@ #include "Encoding.h" #include "FormatToken.h" +#include "clang/Basic/LangOptions.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Basic/SourceManager.h" +#include "clang/Format/Format.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringSet.h" +#include "llvm/Support/Regex.h" #include @@ -115,6 +120,7 @@ class FormatTokenLexer { unsigned Column; unsigned TrailingWhitespace; std::unique_ptr Lex; + LangOptions LangOpts; const SourceManager &SourceMgr; FileID ID; const FormatStyle &Style; diff --git a/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp b/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp index 3c2ceddd5599cf..87823ae32b1138 100644 --- a/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp +++ b/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp @@ -79,7 +79,7 @@ IntegerLiteralSeparatorFixer::process(const Environment &Env, AffectedRangeManager AffectedRangeMgr(SourceMgr, Env.getCharRanges()); const auto ID = Env.getFileID(); - assert(LangOpts.CPlusPlus); + const auto LangOpts = getFormattingLangOpts(Style); Lexer Lex(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts); Lex.SetCommentRetentionState(true); diff --git a/clang/lib/Format/TokenAnalyzer.cpp b/clang/lib/Format/TokenAnalyzer.cpp index f9d1fdb86f1ae9..bd648c430f9b0a 100644 --- a/clang/lib/Format/TokenAnalyzer.cpp +++ b/clang/lib/Format/TokenAnalyzer.cpp @@ -35,8 +35,6 @@ namespace clang { namespace format { -LangOptions LangOpts; - // FIXME: Instead of printing the diagnostic we should store it and have a // better way to return errors through the format APIs. class FatalDiagnosticConsumer : public DiagnosticConsumer { @@ -101,11 +99,9 @@ TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style) std::pair TokenAnalyzer::process(bool SkipAnnotation) { - LangOpts = getFormattingLangOpts(Style); - tooling::Replacements Result; llvm::SpecificBumpP
[clang] [Driver] Remove "-android" from compiler-rt library names for legacy LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=off (PR #81044)
https://github.com/MaskRay closed https://github.com/llvm/llvm-project/pull/81044 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][InstallAPI] Add input file support to library (PR #81701)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Cyndy Ishida (cyndyishida) Changes This patch adds support for expected InstallAPI inputs. InstallAPI accepts a well defined filelist of headers and how those headers represent a single library. InstallAPI captures header files to determine linkable symbols to then compare against what was compiled in a binary dylib and generate TBD files. --- Patch is 25.59 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/81701.diff 10 Files Affected: - (added) clang/include/clang/InstallAPI/FileList.h (+80) - (added) clang/include/clang/InstallAPI/HeaderFile.h (+69) - (modified) clang/lib/ExtractAPI/ExtractAPIConsumer.cpp (+2-4) - (modified) clang/lib/InstallAPI/CMakeLists.txt (+2) - (added) clang/lib/InstallAPI/FileList.cpp (+215) - (added) clang/lib/InstallAPI/HeaderFile.cpp (+32) - (modified) clang/unittests/CMakeLists.txt (+1) - (added) clang/unittests/InstallAPI/CMakeLists.txt (+9) - (added) clang/unittests/InstallAPI/FileListTest.cpp (+173) - (added) clang/unittests/InstallAPI/HeaderFileTest.cpp (+89) ``diff diff --git a/clang/include/clang/InstallAPI/FileList.h b/clang/include/clang/InstallAPI/FileList.h new file mode 100644 index 00..5639388514b11d --- /dev/null +++ b/clang/include/clang/InstallAPI/FileList.h @@ -0,0 +1,80 @@ +//===- InstallAPI/FileList.h *- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +/// +/// The JSON file list parser is used to communicate input to InstallAPI. +/// +//===--===// + +#ifndef LLVM_CLANG_INSTALLAPI_FILELIST_H +#define LLVM_CLANG_INSTALLAPI_FILELIST_H + +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/FileManager.h" +#include "clang/InstallAPI/HeaderFile.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/MemoryBuffer.h" + +namespace clang { +namespace installapi { + +/// Abstract Interface for reading FileList JSON Input. +class FileListReader { + class Implementation; + + Implementation &Impl; + + FileListReader(std::unique_ptr InputBuffer, + llvm::Error &Err); + +public: + static llvm::Expected> + get(std::unique_ptr InputBuffer); + + ~FileListReader(); + + FileListReader(const FileListReader &) = delete; + FileListReader &operator=(const FileListReader &) = delete; + + int getVersion() const; + + struct HeaderInfo { +HeaderType Type; +std::string Path; +std::optional Language; + }; + + /// Visitor used when walking the contents of the file list. + class Visitor { + public: +virtual ~Visitor(); + +virtual void visitHeaderFile(HeaderInfo &header) = 0; + }; + + /// Visit the contents of the header list file, passing each entity to the + /// given visitor. It visits in the same order as they appear in the json + /// file. + void visit(Visitor &visitor); +}; + +class FileListVisitor final : public FileListReader::Visitor { + FileManager &FM; + DiagnosticsEngine &Diag; + HeaderSeq &HeaderFiles; + +public: + FileListVisitor(FileManager &FM, DiagnosticsEngine &Diag, + HeaderSeq &HeaderFiles) + : FM(FM), Diag(Diag), HeaderFiles(HeaderFiles) {} + + void visitHeaderFile(FileListReader::HeaderInfo &Header) override; +}; +} // namespace installapi +} // namespace clang + +#endif // LLVM_CLANG_INSTALLAPI_FILELIST_H diff --git a/clang/include/clang/InstallAPI/HeaderFile.h b/clang/include/clang/InstallAPI/HeaderFile.h new file mode 100644 index 00..7aea045b50c363 --- /dev/null +++ b/clang/include/clang/InstallAPI/HeaderFile.h @@ -0,0 +1,69 @@ +//===- InstallAPI/HeaderFile.h --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +/// +/// Representations of a library's headers for InstallAPI. +/// +//===--===// + +#ifndef LLVM_CLANG_INSTALLAPI_HEADERFILE_H +#define LLVM_CLANG_INSTALLAPI_HEADERFILE_H + +#include "clang/Basic/LangStandard.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Regex.h" +#include +#include + +namespace clang::installapi { + +const llvm::Regex DarwinFwkHeaderRule("/(.+)\\.framework/(.+)?Headers/(.+)"); + +enum class HeaderType { + /// Represents declarations accessible to all clients. + Public, + /// Represents declarations accessible to a disclosed set of clients. + Private, + /// Repr
[clang] [clang][InstallAPI] Add input file support to library (PR #81701)
https://github.com/cyndyishida created https://github.com/llvm/llvm-project/pull/81701 This patch adds support for expected InstallAPI inputs. InstallAPI accepts a well defined filelist of headers and how those headers represent a single library. InstallAPI captures header files to determine linkable symbols to then compare against what was compiled in a binary dylib and generate TBD files. >From a994b56753c424453c4ce4bbeafb0f7211f387b4 Mon Sep 17 00:00:00 2001 From: Cyndy Ishida Date: Tue, 13 Feb 2024 18:22:23 -0800 Subject: [PATCH] [clang][InstallAPI] Add input file support to library This patch adds support for expected InstallAPI inputs. InstallAPI accepts a well defined filelist of headers and how those headers represent a single library. InstallAPI captures header files to determine linkable symbols to then compare against what was compiled in a binary dylib and generate TBD files. --- clang/include/clang/InstallAPI/FileList.h | 80 +++ clang/include/clang/InstallAPI/HeaderFile.h | 69 ++ clang/lib/ExtractAPI/ExtractAPIConsumer.cpp | 6 +- clang/lib/InstallAPI/CMakeLists.txt | 2 + clang/lib/InstallAPI/FileList.cpp | 215 ++ clang/lib/InstallAPI/HeaderFile.cpp | 32 +++ clang/unittests/CMakeLists.txt| 1 + clang/unittests/InstallAPI/CMakeLists.txt | 9 + clang/unittests/InstallAPI/FileListTest.cpp | 173 ++ clang/unittests/InstallAPI/HeaderFileTest.cpp | 89 10 files changed, 672 insertions(+), 4 deletions(-) create mode 100644 clang/include/clang/InstallAPI/FileList.h create mode 100644 clang/include/clang/InstallAPI/HeaderFile.h create mode 100644 clang/lib/InstallAPI/FileList.cpp create mode 100644 clang/lib/InstallAPI/HeaderFile.cpp create mode 100644 clang/unittests/InstallAPI/CMakeLists.txt create mode 100644 clang/unittests/InstallAPI/FileListTest.cpp create mode 100644 clang/unittests/InstallAPI/HeaderFileTest.cpp diff --git a/clang/include/clang/InstallAPI/FileList.h b/clang/include/clang/InstallAPI/FileList.h new file mode 100644 index 00..5639388514b11d --- /dev/null +++ b/clang/include/clang/InstallAPI/FileList.h @@ -0,0 +1,80 @@ +//===- InstallAPI/FileList.h *- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +/// +/// The JSON file list parser is used to communicate input to InstallAPI. +/// +//===--===// + +#ifndef LLVM_CLANG_INSTALLAPI_FILELIST_H +#define LLVM_CLANG_INSTALLAPI_FILELIST_H + +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/FileManager.h" +#include "clang/InstallAPI/HeaderFile.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/MemoryBuffer.h" + +namespace clang { +namespace installapi { + +/// Abstract Interface for reading FileList JSON Input. +class FileListReader { + class Implementation; + + Implementation &Impl; + + FileListReader(std::unique_ptr InputBuffer, + llvm::Error &Err); + +public: + static llvm::Expected> + get(std::unique_ptr InputBuffer); + + ~FileListReader(); + + FileListReader(const FileListReader &) = delete; + FileListReader &operator=(const FileListReader &) = delete; + + int getVersion() const; + + struct HeaderInfo { +HeaderType Type; +std::string Path; +std::optional Language; + }; + + /// Visitor used when walking the contents of the file list. + class Visitor { + public: +virtual ~Visitor(); + +virtual void visitHeaderFile(HeaderInfo &header) = 0; + }; + + /// Visit the contents of the header list file, passing each entity to the + /// given visitor. It visits in the same order as they appear in the json + /// file. + void visit(Visitor &visitor); +}; + +class FileListVisitor final : public FileListReader::Visitor { + FileManager &FM; + DiagnosticsEngine &Diag; + HeaderSeq &HeaderFiles; + +public: + FileListVisitor(FileManager &FM, DiagnosticsEngine &Diag, + HeaderSeq &HeaderFiles) + : FM(FM), Diag(Diag), HeaderFiles(HeaderFiles) {} + + void visitHeaderFile(FileListReader::HeaderInfo &Header) override; +}; +} // namespace installapi +} // namespace clang + +#endif // LLVM_CLANG_INSTALLAPI_FILELIST_H diff --git a/clang/include/clang/InstallAPI/HeaderFile.h b/clang/include/clang/InstallAPI/HeaderFile.h new file mode 100644 index 00..7aea045b50c363 --- /dev/null +++ b/clang/include/clang/InstallAPI/HeaderFile.h @@ -0,0 +1,69 @@ +//===- InstallAPI/HeaderFile.h --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENS
[clang] [HIP] Allow partial linking for `-fgpu-rdc` (PR #81700)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff ec5f4a4bc6f27b044bc73668414ecefe9690d283 318117089831345caa13d8b4eeea23d0aa2c8588 -- clang/lib/CodeGen/CGCUDANV.cpp clang/lib/CodeGen/CodeGenModule.cpp clang/lib/Driver/ToolChains/HIPUtility.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp index 7d23f94473..49f93451db 100644 --- a/clang/lib/CodeGen/CGCUDANV.cpp +++ b/clang/lib/CodeGen/CGCUDANV.cpp @@ -827,7 +827,7 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { GpuBinaryHandle = new llvm::GlobalVariable( TheModule, PtrTy, /*isConstant=*/false, Linkage, /*Initializer=*/ -CudaGpuBinary ? llvm::ConstantPointerNull::get(PtrTy) : nullptr, +CudaGpuBinary ? llvm::ConstantPointerNull::get(PtrTy) : nullptr, CudaGpuBinary ? "__hip_gpubin_handle" : "__hip_gpubin_handle_" + CGM.getContext().getCUIDHash()); diff --git a/clang/lib/Driver/ToolChains/HIPUtility.cpp b/clang/lib/Driver/ToolChains/HIPUtility.cpp index 4bd6926ec6..67519a8a54 100644 --- a/clang/lib/Driver/ToolChains/HIPUtility.cpp +++ b/clang/lib/Driver/ToolChains/HIPUtility.cpp @@ -56,7 +56,7 @@ public: DiagnosticsEngine::Error, "Error collecting HIP undefined fatbin symbols: %0")), Quiet(C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)), -Verbose(C.getArgs().hasArg(options::OPT_v)){ +Verbose(C.getArgs().hasArg(options::OPT_v)) { populateSymbols(); if (Verbose) { for (auto Name : FatBinSymbols) @@ -284,17 +284,12 @@ void HIP::constructGenerateObjFileFromHIPFatBinary( HIPUndefinedFatBinSymbols Symbols(C); std::string PrimaryHipFatbinSymbol; - std::string - PrimaryGpuBinHandleSymbol; - bool FoundPrimaryHipFatbinSymbol = - false; - bool FoundPrimaryGpuBinHandleSymbol = - false; - - std::vector - AliasHipFatbinSymbols; - std::vector - AliasGpuBinHandleSymbols; + std::string PrimaryGpuBinHandleSymbol; + bool FoundPrimaryHipFatbinSymbol = false; + bool FoundPrimaryGpuBinHandleSymbol = false; + + std::vector AliasHipFatbinSymbols; + std::vector AliasGpuBinHandleSymbols; // Iterate through symbols to find the primary ones and collect others for // aliasing `` https://github.com/llvm/llvm-project/pull/81700 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HIP] Allow partial linking for `-fgpu-rdc` (PR #81700)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Yaxun (Sam) Liu (yxsamliu) Changes `-fgpu-rdc` mode allows device functions call device functions in different TU. However, currently all device objects have to be linked together since only one fat binary is supported. This is time consuming for AMDGPU backend since it only supports LTO. There are use cases that objects can be divided into groups in which device functions are self-contained but host functions are not. It is desirable to link/optimize/codegen the device code and generate a fatbin for each group, whereas partially link the host code with `ld -r` or generate a static library by using the `-emit-static-lib` option of clang. This avoids linking all device code together, therefore decreases the linking time for `-fgpu-rdc`. Previously, clang emits an external symbol `__hip_fatbin` for all objects for `-fgpu-rdc`. With this patch, clang emits an unique external symbol `__hip_fatbin_{cuid}` for the fat binary for each object. When a group of objects are linked together to generate a fatbin, the symbols are merged by alias and point to the same fat binary. Each group has its own fat binary. One executable or shared library can have multiple fat binaries. Device linking is done for undefined fab binary symbols only to avoid repeated linking. `__hip_gpubin_handle` is also uniquefied and merged to avoid repeated registering. Symbol `__hip_cuid_{cuid}` is introduced to facilitate debugging and tooling. Fixes: https://github.com/llvm/llvm-project/issues/77018 --- Full diff: https://github.com/llvm/llvm-project/pull/81700.diff 6 Files Affected: - (modified) clang/lib/CodeGen/CGCUDANV.cpp (+11-11) - (modified) clang/lib/CodeGen/CodeGenModule.cpp (+9-1) - (modified) clang/lib/Driver/ToolChains/HIPUtility.cpp (+229-13) - (modified) clang/test/CodeGenCUDA/device-stub.cu (+4-6) - (modified) clang/test/CodeGenCUDA/host-used-device-var.cu (+3-2) - (modified) clang/test/Driver/hip-toolchain-rdc.hip (+27-11) ``diff diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp index 5b43272bfa62f4..7d23f944732dbf 100644 --- a/clang/lib/CodeGen/CGCUDANV.cpp +++ b/clang/lib/CodeGen/CGCUDANV.cpp @@ -760,10 +760,10 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { // to contain the fat binary but will be populated somewhere else, // e.g. by lld through link script. FatBinStr = new llvm::GlobalVariable( -CGM.getModule(), CGM.Int8Ty, -/*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, -"__hip_fatbin", nullptr, -llvm::GlobalVariable::NotThreadLocal); + CGM.getModule(), CGM.Int8Ty, + /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, + "__hip_fatbin_" + CGM.getContext().getCUIDHash(), nullptr, + llvm::GlobalVariable::NotThreadLocal); cast(FatBinStr)->setSection(FatbinConstantName); } @@ -816,8 +816,8 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { // thread safety of the loaded program. Therefore we can assume sequential // execution of constructor functions here. if (IsHIP) { -auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage : -llvm::GlobalValue::LinkOnceAnyLinkage; +auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage + : llvm::GlobalValue::ExternalLinkage; llvm::BasicBlock *IfBlock = llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc); llvm::BasicBlock *ExitBlock = @@ -826,11 +826,11 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { // of HIP ABI. GpuBinaryHandle = new llvm::GlobalVariable( TheModule, PtrTy, /*isConstant=*/false, Linkage, -/*Initializer=*/llvm::ConstantPointerNull::get(PtrTy), -"__hip_gpubin_handle"); -if (Linkage == llvm::GlobalValue::LinkOnceAnyLinkage) - GpuBinaryHandle->setComdat( - CGM.getModule().getOrInsertComdat(GpuBinaryHandle->getName())); +/*Initializer=*/ +CudaGpuBinary ? llvm::ConstantPointerNull::get(PtrTy) : nullptr, +CudaGpuBinary +? "__hip_gpubin_handle" +: "__hip_gpubin_handle_" + CGM.getContext().getCUIDHash()); GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign()); // Prevent the weak symbol in different shared libraries being merged. if (Linkage != llvm::GlobalValue::InternalLinkage) diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index c984260b082cd1..218066bced6c19 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -919,7 +919,15 @@ void CodeGenModule::Release() { llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); addCompilerUsedGlobal(GV); } - + if (LangOpts.HIP) { +// Emit a unique ID so that host and device binaries from the same
[clang] [HIP] Allow partial linking for `-fgpu-rdc` (PR #81700)
https://github.com/yxsamliu created https://github.com/llvm/llvm-project/pull/81700 `-fgpu-rdc` mode allows device functions call device functions in different TU. However, currently all device objects have to be linked together since only one fat binary is supported. This is time consuming for AMDGPU backend since it only supports LTO. There are use cases that objects can be divided into groups in which device functions are self-contained but host functions are not. It is desirable to link/optimize/codegen the device code and generate a fatbin for each group, whereas partially link the host code with `ld -r` or generate a static library by using the `-emit-static-lib` option of clang. This avoids linking all device code together, therefore decreases the linking time for `-fgpu-rdc`. Previously, clang emits an external symbol `__hip_fatbin` for all objects for `-fgpu-rdc`. With this patch, clang emits an unique external symbol `__hip_fatbin_{cuid}` for the fat binary for each object. When a group of objects are linked together to generate a fatbin, the symbols are merged by alias and point to the same fat binary. Each group has its own fat binary. One executable or shared library can have multiple fat binaries. Device linking is done for undefined fab binary symbols only to avoid repeated linking. `__hip_gpubin_handle` is also uniquefied and merged to avoid repeated registering. Symbol `__hip_cuid_{cuid}` is introduced to facilitate debugging and tooling. Fixes: https://github.com/llvm/llvm-project/issues/77018 >From 318117089831345caa13d8b4eeea23d0aa2c8588 Mon Sep 17 00:00:00 2001 From: "Yaxun (Sam) Liu" Date: Tue, 13 Feb 2024 10:00:21 -0500 Subject: [PATCH] [HIP] Allow partial linking for `-fgpu-rdc` `-fgpu-rdc` mode allows device functions call device functions in different TU. However, currently all device objects have to be linked together since only one fat binary is supported. This is time consuming for AMDGPU backend since it only supports LTO. There are use cases that objects can be divided into groups in which device functions are self-contained but host functions are not. It is desirable to link/optimize/codegen the device code and generate a fatbin for each group, whereas partially link the host code with `ld -r` or generate a static library by using the `-emit-static-lib` option of clang. This avoids linking all device code together, therefore decreases the linking time for `-fgpu-rdc`. Previously, clang emits an external symbol `__hip_fatbin` for all objects for `-fgpu-rdc`. With this patch, clang emits an unique external symbol `__hip_fatbin_{cuid}` for the fat binary for each object. When a group of objects are linked together to generate a fatbin, the symbols are merged by alias and point to the same fat binary. Each group has its own fat binary. One executable or shared library can have multiple fat binaries. Device linking is done for undefined fab binary symbols only to avoid repeated linking. `__hip_gpubin_handle` is also uniquefied and merged to avoid repeated registering. Symbol `__hip_cuid_{cuid}` is introduced to facilitate debugging and tooling. Fixes: https://github.com/llvm/llvm-project/issues/77018 --- clang/lib/CodeGen/CGCUDANV.cpp| 22 +- clang/lib/CodeGen/CodeGenModule.cpp | 10 +- clang/lib/Driver/ToolChains/HIPUtility.cpp| 242 +- clang/test/CodeGenCUDA/device-stub.cu | 10 +- .../test/CodeGenCUDA/host-used-device-var.cu | 5 +- clang/test/Driver/hip-toolchain-rdc.hip | 38 ++- 6 files changed, 283 insertions(+), 44 deletions(-) diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp index 5b43272bfa62f4..7d23f944732dbf 100644 --- a/clang/lib/CodeGen/CGCUDANV.cpp +++ b/clang/lib/CodeGen/CGCUDANV.cpp @@ -760,10 +760,10 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { // to contain the fat binary but will be populated somewhere else, // e.g. by lld through link script. FatBinStr = new llvm::GlobalVariable( -CGM.getModule(), CGM.Int8Ty, -/*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, -"__hip_fatbin", nullptr, -llvm::GlobalVariable::NotThreadLocal); + CGM.getModule(), CGM.Int8Ty, + /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, + "__hip_fatbin_" + CGM.getContext().getCUIDHash(), nullptr, + llvm::GlobalVariable::NotThreadLocal); cast(FatBinStr)->setSection(FatbinConstantName); } @@ -816,8 +816,8 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { // thread safety of the loaded program. Therefore we can assume sequential // execution of constructor functions here. if (IsHIP) { -auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage : -llvm::GlobalValue::LinkOnceAnyLinkage; +auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage +
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/81400 >From 6f94c583f5201fbd73156969fa410669d6e1be93 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Tue, 13 Feb 2024 20:05:18 -0800 Subject: [PATCH 1/3] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. This PR makes alpha.webkit.UncountedCallArgsChecker eplicitly check the safety of the object argument in a member function call. --- .../WebKit/UncountedCallArgsChecker.cpp | 67 +-- .../Checkers/WebKit/uncounted-obj-arg.cpp | 18 + 2 files changed, 66 insertions(+), 19 deletions(-) create mode 100644 clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp index f4e6191cf05a3c..d4bf3e2c2e75db 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp @@ -70,6 +70,15 @@ class UncountedCallArgsChecker // or std::function call operator). unsigned ArgIdx = isa(CE) && isa_and_nonnull(F); + if (auto *MemberCallExpr = dyn_cast(CE)) { +auto *E = MemberCallExpr->getImplicitObjectArgument(); +auto *ArgType = MemberCallExpr->getObjectType().getTypePtrOrNull(); +std::optional IsUncounted = +isUncounted(ArgType->getAsCXXRecordDecl()); +if (IsUncounted && *IsUncounted && !isPtrOriginSafe(E)) + reportBugOnThis(E); + } + for (auto P = F->param_begin(); // FIXME: Also check variadic function parameters. // FIXME: Also check default function arguments. Probably a different @@ -94,25 +103,7 @@ class UncountedCallArgsChecker if (auto *defaultArg = dyn_cast(Arg)) Arg = defaultArg->getExpr(); -std::pair ArgOrigin = -tryToFindPtrOrigin(Arg, true); - -// Temporary ref-counted object created as part of the call argument -// would outlive the call. -if (ArgOrigin.second) - continue; - -if (isa(ArgOrigin.first)) { - // foo(nullptr) - continue; -} -if (isa(ArgOrigin.first)) { - // FIXME: Check the value. - // foo(NULL) - continue; -} - -if (isASafeCallArg(ArgOrigin.first)) +if (isPtrOriginSafe(Arg)) continue; reportBug(Arg, *P); @@ -120,6 +111,28 @@ class UncountedCallArgsChecker } } + bool isPtrOriginSafe(const Expr *Arg) const { +std::pair ArgOrigin = +tryToFindPtrOrigin(Arg, true); + +// Temporary ref-counted object created as part of the call argument +// would outlive the call. +if (ArgOrigin.second) + return true; + +if (isa(ArgOrigin.first)) { + // foo(nullptr) + return true; +} +if (isa(ArgOrigin.first)) { + // FIXME: Check the value. + // foo(NULL) + return true; +} + +return isASafeCallArg(ArgOrigin.first); + } + bool shouldSkipCall(const CallExpr *CE) const { if (CE->getNumArgs() == 0) return false; @@ -196,6 +209,22 @@ class UncountedCallArgsChecker Report->addRange(CallArg->getSourceRange()); BR->emitReport(std::move(Report)); } + + void reportBugOnThis(const Expr *CallArg) const { +assert(CallArg); + +SmallString<100> Buf; +llvm::raw_svector_ostream Os(Buf); + +Os << "Call argument for 'this' parameter is uncounted and unsafe."; + +const SourceLocation SrcLocToReport = CallArg->getSourceRange().getBegin(); + +PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager()); +auto Report = std::make_unique(Bug, Os.str(), BSLoc); +Report->addRange(CallArg->getSourceRange()); +BR->emitReport(std::move(Report)); + } }; } // namespace diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp new file mode 100644 index 00..e5e39e3faac714 --- /dev/null +++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp @@ -0,0 +1,18 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s + +#include "mock-types.h" + +class RefCounted { +public: + void ref() const; + void deref() const; + void someFunction(); +}; + +RefCounted* refCountedObj(); + +void test() +{ + refCountedObj()->someFunction(); + // expected-warning@-1{{Call argument for 'this' parameter is uncounted and unsafe}} +} >From c15967f8f09198c01aec8b0161cc08484c78f66a Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Tue, 13 Feb 2024 19:36:09 -0800 Subject: [PATCH 2/3] Address the review comment. Namely avoid calling getTypePtrOrNull and don't use raw_svector_ostream. --- .../Checkers/WebKit/UncountedCallArgsChecker.cpp | 9 ++--- 1 file chang
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
rniwa wrote: Rebased. https://github.com/llvm/llvm-project/pull/81400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/81400 >From 6f94c583f5201fbd73156969fa410669d6e1be93 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Tue, 13 Feb 2024 20:05:18 -0800 Subject: [PATCH 1/2] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. This PR makes alpha.webkit.UncountedCallArgsChecker eplicitly check the safety of the object argument in a member function call. --- .../WebKit/UncountedCallArgsChecker.cpp | 67 +-- .../Checkers/WebKit/uncounted-obj-arg.cpp | 18 + 2 files changed, 66 insertions(+), 19 deletions(-) create mode 100644 clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp index f4e6191cf05a3c..d4bf3e2c2e75db 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp @@ -70,6 +70,15 @@ class UncountedCallArgsChecker // or std::function call operator). unsigned ArgIdx = isa(CE) && isa_and_nonnull(F); + if (auto *MemberCallExpr = dyn_cast(CE)) { +auto *E = MemberCallExpr->getImplicitObjectArgument(); +auto *ArgType = MemberCallExpr->getObjectType().getTypePtrOrNull(); +std::optional IsUncounted = +isUncounted(ArgType->getAsCXXRecordDecl()); +if (IsUncounted && *IsUncounted && !isPtrOriginSafe(E)) + reportBugOnThis(E); + } + for (auto P = F->param_begin(); // FIXME: Also check variadic function parameters. // FIXME: Also check default function arguments. Probably a different @@ -94,25 +103,7 @@ class UncountedCallArgsChecker if (auto *defaultArg = dyn_cast(Arg)) Arg = defaultArg->getExpr(); -std::pair ArgOrigin = -tryToFindPtrOrigin(Arg, true); - -// Temporary ref-counted object created as part of the call argument -// would outlive the call. -if (ArgOrigin.second) - continue; - -if (isa(ArgOrigin.first)) { - // foo(nullptr) - continue; -} -if (isa(ArgOrigin.first)) { - // FIXME: Check the value. - // foo(NULL) - continue; -} - -if (isASafeCallArg(ArgOrigin.first)) +if (isPtrOriginSafe(Arg)) continue; reportBug(Arg, *P); @@ -120,6 +111,28 @@ class UncountedCallArgsChecker } } + bool isPtrOriginSafe(const Expr *Arg) const { +std::pair ArgOrigin = +tryToFindPtrOrigin(Arg, true); + +// Temporary ref-counted object created as part of the call argument +// would outlive the call. +if (ArgOrigin.second) + return true; + +if (isa(ArgOrigin.first)) { + // foo(nullptr) + return true; +} +if (isa(ArgOrigin.first)) { + // FIXME: Check the value. + // foo(NULL) + return true; +} + +return isASafeCallArg(ArgOrigin.first); + } + bool shouldSkipCall(const CallExpr *CE) const { if (CE->getNumArgs() == 0) return false; @@ -196,6 +209,22 @@ class UncountedCallArgsChecker Report->addRange(CallArg->getSourceRange()); BR->emitReport(std::move(Report)); } + + void reportBugOnThis(const Expr *CallArg) const { +assert(CallArg); + +SmallString<100> Buf; +llvm::raw_svector_ostream Os(Buf); + +Os << "Call argument for 'this' parameter is uncounted and unsafe."; + +const SourceLocation SrcLocToReport = CallArg->getSourceRange().getBegin(); + +PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager()); +auto Report = std::make_unique(Bug, Os.str(), BSLoc); +Report->addRange(CallArg->getSourceRange()); +BR->emitReport(std::move(Report)); + } }; } // namespace diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp new file mode 100644 index 00..e5e39e3faac714 --- /dev/null +++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp @@ -0,0 +1,18 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s + +#include "mock-types.h" + +class RefCounted { +public: + void ref() const; + void deref() const; + void someFunction(); +}; + +RefCounted* refCountedObj(); + +void test() +{ + refCountedObj()->someFunction(); + // expected-warning@-1{{Call argument for 'this' parameter is uncounted and unsafe}} +} >From c15967f8f09198c01aec8b0161cc08484c78f66a Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Tue, 13 Feb 2024 19:36:09 -0800 Subject: [PATCH 2/2] Address the review comment. Namely avoid calling getTypePtrOrNull and don't use raw_svector_ostream. --- .../Checkers/WebKit/UncountedCallArgsChecker.cpp | 9 ++--- 1 file chang
[clang] [Clang][CodeGen] Loose the cast check when emitting builtins (PR #81669)
shiltian wrote: > I can't tell what you're trying to fix here. Is this fixing a crash? Or is > the check redundant? Or is it necessary for some followup change you want to > make? Sorry, I should have clearly mentioned that. Yes, it is for my followup change #80908. In #80908, we changed the type of LLVM builtin but kept the corresponding clang builtin unchanged to avoid breaking existing uses. Specifically, the original builtin accepts some `bfloat` arguments (either `bfloat` or `<2 x bfloat>`) and returns a `bfloat` value. Because of some historic reasons, the builtin uses `i16` to represent `bfloat` values, and the backend just treats the 16 bits as `bfloat`. Now we encountered some issues that motivated us to use the right type here, but we still want to maintain sort of backward compatibility, at least on user-facing level. Keeping the corresponding clang builtin unchanged is the path we chose. Given that, it requires the front end to emit corresponding bitcast because the type `i16` and `bfloat` (and the vec type) are not matched. `EmitBuiltinExpr` is capable of doing that, but the bitcast check here prevents it from doing it. `canLosslesslyBitCastTo` doesn't think bitcast from `i16` to `bf16` and vice versa are lossless. I was thinking of just allowing this specific cast in `canLosslesslyBitCastTo` but I figured that doesn't look very good. On a second thought, it looks like the check here is too conservative. https://github.com/llvm/llvm-project/pull/81669 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Detect a return value of Ref & RefPtr (PR #81580)
https://github.com/haoNoQ approved this pull request. LGTM! https://github.com/llvm/llvm-project/pull/81580 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
https://github.com/haoNoQ approved this pull request. Great! Needs a rebase now though. https://github.com/llvm/llvm-project/pull/81400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
@@ -183,6 +196,22 @@ class UncountedCallArgsChecker Report->addRange(CallArg->getSourceRange()); BR->emitReport(std::move(Report)); } + + void reportBugOnThis(const Expr *CallArg) const { +assert(CallArg); + +SmallString<100> Buf; +llvm::raw_svector_ostream Os(Buf); + +Os << "Call argument for 'this' parameter is uncounted and unsafe."; rniwa wrote: Good point. Fixed. https://github.com/llvm/llvm-project/pull/81400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/81400 >From 04e18254efc4f671e0bbd9625c7e994fe47c1636 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Sun, 11 Feb 2024 00:07:30 -0800 Subject: [PATCH 1/2] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. This PR makes alpha.webkit.UncountedCallArgsChecker eplicitly check the safety of the object argument in a member function call. --- .../WebKit/UncountedCallArgsChecker.cpp | 67 +-- .../Checkers/WebKit/uncounted-obj-arg.cpp | 18 + 2 files changed, 66 insertions(+), 19 deletions(-) create mode 100644 clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp index 31ccae8b097b89..cda96b70ea8735 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp @@ -70,6 +70,15 @@ class UncountedCallArgsChecker // or std::function call operator). unsigned ArgIdx = isa(CE) && isa_and_nonnull(F); + if (auto *MemberCallExpr = dyn_cast(CE)) { +auto *E = MemberCallExpr->getImplicitObjectArgument(); +auto *ArgType = MemberCallExpr->getObjectType().getTypePtrOrNull(); +std::optional IsUncounted = +isUncounted(ArgType->getAsCXXRecordDecl()); +if (IsUncounted && *IsUncounted && !isPtrOriginSafe(E)) + reportBugOnThis(E); + } + for (auto P = F->param_begin(); // FIXME: Also check variadic function parameters. // FIXME: Also check default function arguments. Probably a different @@ -91,25 +100,7 @@ class UncountedCallArgsChecker const auto *Arg = CE->getArg(ArgIdx); -std::pair ArgOrigin = -tryToFindPtrOrigin(Arg, true); - -// Temporary ref-counted object created as part of the call argument -// would outlive the call. -if (ArgOrigin.second) - continue; - -if (isa(ArgOrigin.first)) { - // foo(nullptr) - continue; -} -if (isa(ArgOrigin.first)) { - // FIXME: Check the value. - // foo(NULL) - continue; -} - -if (isASafeCallArg(ArgOrigin.first)) +if (isPtrOriginSafe(Arg)) continue; reportBug(Arg, *P); @@ -117,6 +108,28 @@ class UncountedCallArgsChecker } } + bool isPtrOriginSafe(const Expr *Arg) const { +std::pair ArgOrigin = +tryToFindPtrOrigin(Arg, true); + +// Temporary ref-counted object created as part of the call argument +// would outlive the call. +if (ArgOrigin.second) + return true; + +if (isa(ArgOrigin.first)) { + // foo(nullptr) + return true; +} +if (isa(ArgOrigin.first)) { + // FIXME: Check the value. + // foo(NULL) + return true; +} + +return isASafeCallArg(ArgOrigin.first); + } + bool shouldSkipCall(const CallExpr *CE) const { if (CE->getNumArgs() == 0) return false; @@ -183,6 +196,22 @@ class UncountedCallArgsChecker Report->addRange(CallArg->getSourceRange()); BR->emitReport(std::move(Report)); } + + void reportBugOnThis(const Expr *CallArg) const { +assert(CallArg); + +SmallString<100> Buf; +llvm::raw_svector_ostream Os(Buf); + +Os << "Call argument for 'this' parameter is uncounted and unsafe."; + +const SourceLocation SrcLocToReport = CallArg->getSourceRange().getBegin(); + +PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager()); +auto Report = std::make_unique(Bug, Os.str(), BSLoc); +Report->addRange(CallArg->getSourceRange()); +BR->emitReport(std::move(Report)); + } }; } // namespace diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp new file mode 100644 index 00..e5e39e3faac714 --- /dev/null +++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp @@ -0,0 +1,18 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s + +#include "mock-types.h" + +class RefCounted { +public: + void ref() const; + void deref() const; + void someFunction(); +}; + +RefCounted* refCountedObj(); + +void test() +{ + refCountedObj()->someFunction(); + // expected-warning@-1{{Call argument for 'this' parameter is uncounted and unsafe}} +} >From 2d780389a46e5c053053c1432d2ec3af2a7653e9 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Tue, 13 Feb 2024 19:36:09 -0800 Subject: [PATCH 2/2] Address the review comment. Namely avoid calling getTypePtrOrNull and don't use raw_svector_ostream. --- .../Checkers/WebKit/UncountedCallArgsChecker.cpp | 9 ++--- 1 file changed, 2 insertions(+), 7 deletions(-) d
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
@@ -70,6 +70,15 @@ class UncountedCallArgsChecker // or std::function call operator). unsigned ArgIdx = isa(CE) && isa_and_nonnull(F); + if (auto *MemberCallExpr = dyn_cast(CE)) { +auto *E = MemberCallExpr->getImplicitObjectArgument(); +auto *ArgType = MemberCallExpr->getObjectType().getTypePtrOrNull(); rniwa wrote: Ah, okay. Will do that. https://github.com/llvm/llvm-project/pull/81400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Detect a return value of Ref & RefPtr (PR #81580)
@@ -118,6 +118,26 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F) { || FunctionName == "Identifier"; } +bool isReturnValueRefCounted(const clang::FunctionDecl *F) { + assert(F); + auto *type = F->getReturnType().getTypePtrOrNull(); + while (type) { +if (auto *elaboratedT = dyn_cast(type)) { + type = elaboratedT->desugar().getTypePtrOrNull(); + continue; +} +if (auto *specialT = dyn_cast(type)) { rniwa wrote: Sounds good. Fixed. https://github.com/llvm/llvm-project/pull/81580 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Detect a return value of Ref & RefPtr (PR #81580)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/81580 >From 24fc75756094d36e72c69805c9d476d8144ed869 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Tue, 13 Feb 2024 00:35:36 -0800 Subject: [PATCH 1/2] [alpha.webkit.UncountedCallArgsChecker] Detect a return value of `Ref` & `RefPtr` This PR makes the checker not emit warning when a function is called with a return value of another function when the return value is of type `Ref` or `RefPtr`. --- .../Checkers/WebKit/ASTUtils.cpp | 6 + .../Checkers/WebKit/PtrTypesSemantics.cpp | 20 .../Checkers/WebKit/PtrTypesSemantics.h | 3 +++ .../call-args-protected-return-value.cpp | 23 +++ .../Analysis/Checkers/WebKit/mock-types.h | 1 + 5 files changed, 53 insertions(+) create mode 100644 clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp index 4526fac64735bf..b76c0551c77bb0 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp @@ -19,6 +19,10 @@ namespace clang { std::pair tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) { while (E) { +if (auto *tempExpr = dyn_cast(E)) { + E = tempExpr->getSubExpr(); + continue; +} if (auto *cast = dyn_cast(E)) { if (StopAtFirstRefCountedObj) { if (auto *ConversionFunc = @@ -62,6 +66,8 @@ tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) { E = call->getArg(0); continue; } +if (isReturnValueRefCounted(callee)) + return {E, true}; if (isPtrConversion(callee)) { E = call->getArg(0); diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp index d2b66341058000..70c94dd0e960ab 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp @@ -118,6 +118,26 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F) { || FunctionName == "Identifier"; } +bool isReturnValueRefCounted(const clang::FunctionDecl *F) { + assert(F); + auto *type = F->getReturnType().getTypePtrOrNull(); + while (type) { +if (auto *elaboratedT = dyn_cast(type)) { + type = elaboratedT->desugar().getTypePtrOrNull(); + continue; +} +if (auto *specialT = dyn_cast(type)) { + if (auto *decl = specialT->getTemplateName().getAsTemplateDecl()) { +auto name = decl->getNameAsString(); +return name == "Ref" || name == "RefPtr"; + } + return false; +} +return false; + } + return false; +} + std::optional isUncounted(const CXXRecordDecl* Class) { // Keep isRefCounted first as it's cheaper. diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h index 45b21cc0918443..c2c5b74442ba43 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h @@ -50,6 +50,9 @@ std::optional isUncountedPtr(const clang::Type* T); /// false if not. bool isCtorOfRefCounted(const clang::FunctionDecl *F); +/// \returns true if \p F returns a ref-counted object, false if not. +bool isReturnValueRefCounted(const clang::FunctionDecl *F); + /// \returns true if \p M is getter of a ref-counted class, false if not. std::optional isGetterOfRefCounted(const clang::CXXMethodDecl* Method); diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp b/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp new file mode 100644 index 00..1c4b3df211b1e3 --- /dev/null +++ b/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp @@ -0,0 +1,23 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s +// expected-no-diagnostics + +#include "mock-types.h" + +class RefCounted { +public: + void ref(); + void deref(); +}; + +class Object { +public: + void someFunction(RefCounted&); +}; + +RefPtr object(); +RefPtr protectedTargetObject(); + +void testFunction() { + if (RefPtr obj = object()) +obj->someFunction(*protectedTargetObject()); +} diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h b/clang/test/Analysis/Checkers/WebKit/mock-types.h index 5f570b8bee8cb8..814e0944145992 100644 --- a/clang/test/Analysis/Checkers/WebKit/mock-types.h +++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h @@ -20,6 +20,7 @@ template struct RefPtr { T *operator->() { return t; } T &operator*() { return *t; } RefPtr &operator=(T *) { return *this; } + operator bool() { return t; } }; template bool operator==(const
[clang] [llvm] [openmp] [PGO][OpenMP] Instrumentation for GPU devices (PR #76587)
https://github.com/EthanLuisMcDonough updated https://github.com/llvm/llvm-project/pull/76587 >From 530eb982b9770190377bb0bd09c5cb715f34d484 Mon Sep 17 00:00:00 2001 From: Ethan Luis McDonough Date: Fri, 15 Dec 2023 20:38:38 -0600 Subject: [PATCH 01/13] Add profiling functions to libomptarget --- .../include/llvm/Frontend/OpenMP/OMPKinds.def | 3 +++ openmp/libomptarget/DeviceRTL/CMakeLists.txt | 2 ++ .../DeviceRTL/include/Profiling.h | 21 +++ .../libomptarget/DeviceRTL/src/Profiling.cpp | 19 + 4 files changed, 45 insertions(+) create mode 100644 openmp/libomptarget/DeviceRTL/include/Profiling.h create mode 100644 openmp/libomptarget/DeviceRTL/src/Profiling.cpp diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def b/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def index d22d2a8e948b00..1d887d5cb58127 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def +++ b/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def @@ -503,6 +503,9 @@ __OMP_RTL(__kmpc_barrier_simple_generic, false, Void, IdentPtr, Int32) __OMP_RTL(__kmpc_warp_active_thread_mask, false, Int64,) __OMP_RTL(__kmpc_syncwarp, false, Void, Int64) +__OMP_RTL(__llvm_profile_register_function, false, Void, VoidPtr) +__OMP_RTL(__llvm_profile_register_names_function, false, Void, VoidPtr, Int64) + __OMP_RTL(__last, false, Void, ) #undef __OMP_RTL diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt b/openmp/libomptarget/DeviceRTL/CMakeLists.txt index 1ce3e1e40a80ab..55ee15d068c67b 100644 --- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt +++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt @@ -89,6 +89,7 @@ set(include_files ${include_directory}/Interface.h ${include_directory}/LibC.h ${include_directory}/Mapping.h + ${include_directory}/Profiling.h ${include_directory}/State.h ${include_directory}/Synchronization.h ${include_directory}/Types.h @@ -104,6 +105,7 @@ set(src_files ${source_directory}/Mapping.cpp ${source_directory}/Misc.cpp ${source_directory}/Parallelism.cpp + ${source_directory}/Profiling.cpp ${source_directory}/Reduction.cpp ${source_directory}/State.cpp ${source_directory}/Synchronization.cpp diff --git a/openmp/libomptarget/DeviceRTL/include/Profiling.h b/openmp/libomptarget/DeviceRTL/include/Profiling.h new file mode 100644 index 00..68c7744cd60752 --- /dev/null +++ b/openmp/libomptarget/DeviceRTL/include/Profiling.h @@ -0,0 +1,21 @@ +//=== Profiling.h - OpenMP interface -- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +// +// +//===--===// + +#ifndef OMPTARGET_DEVICERTL_PROFILING_H +#define OMPTARGET_DEVICERTL_PROFILING_H + +extern "C" { + +void __llvm_profile_register_function(void *ptr); +void __llvm_profile_register_names_function(void *ptr, long int i); +} + +#endif diff --git a/openmp/libomptarget/DeviceRTL/src/Profiling.cpp b/openmp/libomptarget/DeviceRTL/src/Profiling.cpp new file mode 100644 index 00..799477f5e47d27 --- /dev/null +++ b/openmp/libomptarget/DeviceRTL/src/Profiling.cpp @@ -0,0 +1,19 @@ +//===--- Profiling.cpp C++ ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "Profiling.h" + +#pragma omp begin declare target device_type(nohost) + +extern "C" { + +void __llvm_profile_register_function(void *ptr) {} +void __llvm_profile_register_names_function(void *ptr, long int i) {} +} + +#pragma omp end declare target >From fb067d4ffe604fd68cf90b705db1942bce49dbb1 Mon Sep 17 00:00:00 2001 From: Ethan Luis McDonough Date: Sat, 16 Dec 2023 01:18:41 -0600 Subject: [PATCH 02/13] Fix PGO instrumentation for GPU targets --- clang/lib/CodeGen/CodeGenPGO.cpp | 10 -- .../lib/Transforms/Instrumentation/InstrProfiling.cpp | 11 --- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/clang/lib/CodeGen/CodeGenPGO.cpp b/clang/lib/CodeGen/CodeGenPGO.cpp index 81bf8ea696b164..edae6885b528ac 100644 --- a/clang/lib/CodeGen/CodeGenPGO.cpp +++ b/clang/lib/CodeGen/CodeGenPGO.cpp @@ -959,8 +959,14 @@ void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S, unsigned Counter = (*RegionCounterMap)[S]; - llvm::Value *Args[] = {FuncNameVar, - Builder.getInt64(FunctionHash), + // Make sure that pointer to global is passed in with zero addrspace + //
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -0,0 +1,8 @@ +# RUN: llvm-mc -triple=amdgcn -mcpu=gfx1100 -disassemble -show-encoding < %s | FileCheck %s +# RUN: llvm-mc -triple=amdgcn -mcpu=gfx1200 -disassemble -show-encoding < %s | FileCheck %s + +# CHECK: v_dot2_bf16_bf16 v5, v1, v2, 0x42c8 +0x05,0x00,0x67,0xd6,0x01,0x05,0xfe,0x03,0xc8,0x42,0x00,0x00 + +# CHECK: v_dot2_bf16_bf16 v5, v1, v2, 0x3c00 shiltian wrote: The disassembler doesn't work properly because when it sees `242` with bitwidth 16, it doesn't know whether it is bf16 or fp16. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
https://github.com/shiltian updated https://github.com/llvm/llvm-project/pull/80908 >From 7a517eeab81b45616dd7a1511380f4696304375a Mon Sep 17 00:00:00 2001 From: Shilei Tian Date: Tue, 13 Feb 2024 21:59:52 -0500 Subject: [PATCH] [RFC][WIP][AMDGPU] Use `bf16` instead of `i16` for bfloat Currently it looks like we generally use `i16` to represent `bf16` in those tablegen files. I'm not sure of the reason behind it. My wild guess is the type `bf16` was not available when we enabled the support. This patch is trying to use `bf16` directly in those tablegen files, aiming at fixing #79369. Of course for #79369 a workaround can be to treat all `INT16` variants as `BFloat` in `getOpFltSemantics`, but it doesn't look good IMHO. Since I'm fairly new to AMDGPU backend, I'd appreciate it if you can point out where I don't understand correctly. --- clang/lib/CodeGen/CGBuiltin.cpp | 4 - .../builtins-amdgcn-dl-insts-gfx11.cl | 5 +- llvm/include/llvm/IR/IntrinsicsAMDGPU.td | 8 +- .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp | 92 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp | 57 .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h | 2 + .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp | 39 llvm/lib/Target/AMDGPU/SIDefines.h| 7 ++ llvm/lib/Target/AMDGPU/SIInstrInfo.cpp| 15 +++ llvm/lib/Target/AMDGPU/SIInstrInfo.td | 58 ++-- llvm/lib/Target/AMDGPU/SIRegisterInfo.td | 21 - .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp| 54 +++ llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h | 16 llvm/lib/Target/AMDGPU/VOP3Instructions.td| 2 +- .../AMDGPU/llvm.amdgcn.fdot2.bf16.bf16.ll | 51 -- llvm/test/MC/AMDGPU/bf16_imm.s| 8 ++ llvm/test/MC/Disassembler/AMDGPU/bf16_imm.txt | 8 ++ 17 files changed, 379 insertions(+), 68 deletions(-) create mode 100644 llvm/test/MC/AMDGPU/bf16_imm.s create mode 100644 llvm/test/MC/Disassembler/AMDGPU/bf16_imm.txt diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index ee0b7504769622..9bc60466d09be6 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -5912,8 +5912,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } -assert(ArgValue->getType()->canLosslesslyBitCastTo(PTy) && - "Must be able to losslessly bit cast to param"); // Cast vector type (e.g., v256i32) to x86_amx, this only happen // in amx intrinsics. if (PTy->isX86_AMXTy()) @@ -5943,8 +5941,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } - assert(V->getType()->canLosslesslyBitCastTo(RetTy) && - "Must be able to losslessly bit cast result type"); // Cast x86_amx to vector type (e.g., v256i32), this only happen // in amx intrinsics. if (V->getType()->isX86_AMXTy()) diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl index dc7069decaaa61..7688dfa55a78e3 100644 --- a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl @@ -11,7 +11,10 @@ typedef unsigned short __attribute__((ext_vector_type(2))) ushort2; // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 true) // CHECK: call half @llvm.amdgcn.fdot2.f16.f16(<2 x half> %v2hA, <2 x half> %v2hB, half %hC) -// CHECK: call i16 @llvm.amdgcn.fdot2.bf16.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, i16 %sC) +// CHECK: [[s1:%[0-9]+]] = bitcast <2 x i16> %v2ssA to <2 x bfloat> +// CHECK-NEXT: [[s2:%[0-9]+]] = bitcast <2 x i16> %v2ssB to <2 x bfloat> +// CHECK-NEXT: [[s3:%[0-9]+]] = bitcast i16 %sC to bfloat +// CHECK-NEXT: [[d:%[0-9]+]] = tail call bfloat @llvm.amdgcn.fdot2.bf16.bf16(<2 x bfloat> [[s1]], <2 x bfloat> [[s2]], bfloat [[s3]]) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 true) // CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 false) diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td index 202fa4e8f4ea81..6795fb7aa0edb8 100644 --- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td +++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td @@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 : def int_amdgcn_fdot2_bf16_bf16 : ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">, DefaultAttrsIntrinsic< -[llvm_i16_ty], // %r +[llvm_bfloat_ty], // %r [ - llvm_v2i16_ty, // %a - llvm_v2i16_ty, // %b - llvm_i16_ty// %c +
[clang] bad error message on incorrect string literal #18079 (PR #81670)
akshaykumars614 wrote: Got it. I will look upon it further. Now should I close this pull request or add the updated commit here itself? https://github.com/llvm/llvm-project/pull/81670 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] ec5f4a4 - [InstallAPI] Add missing link to clangBasic
Author: Cyndy Ishida Date: 2024-02-13T18:59:18-08:00 New Revision: ec5f4a4bc6f27b044bc73668414ecefe9690d283 URL: https://github.com/llvm/llvm-project/commit/ec5f4a4bc6f27b044bc73668414ecefe9690d283 DIFF: https://github.com/llvm/llvm-project/commit/ec5f4a4bc6f27b044bc73668414ecefe9690d283.diff LOG: [InstallAPI] Add missing link to clangBasic Fixes CI. Added: Modified: clang/lib/InstallAPI/CMakeLists.txt Removed: diff --git a/clang/lib/InstallAPI/CMakeLists.txt b/clang/lib/InstallAPI/CMakeLists.txt index b68d8fbbec1d37..1476b737c5e61c 100644 --- a/clang/lib/InstallAPI/CMakeLists.txt +++ b/clang/lib/InstallAPI/CMakeLists.txt @@ -8,4 +8,5 @@ add_clang_library(clangInstallAPI LINK_LIBS clangAST + clangBasic ) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][InstallAPI] Introduce basic driver to write out tbd files (PR #81571)
https://github.com/cyndyishida closed https://github.com/llvm/llvm-project/pull/81571 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 09e9895 - [clang][InstallAPI] Introduce basic driver to write out tbd files (#81571)
Author: Cyndy Ishida Date: 2024-02-13T18:52:11-08:00 New Revision: 09e98950bfcff7ad376922932efb2b56e4db9898 URL: https://github.com/llvm/llvm-project/commit/09e98950bfcff7ad376922932efb2b56e4db9898 DIFF: https://github.com/llvm/llvm-project/commit/09e98950bfcff7ad376922932efb2b56e4db9898.diff LOG: [clang][InstallAPI] Introduce basic driver to write out tbd files (#81571) This introduces a basic outline of installapi as a clang driver option. It captures relevant information as cc1 args, which are common arguments already passed to the linker to encode into TBD file outputs. This is effectively an upstream for what already exists as `tapi installapi` in Xcode toolchains, but directly in Clang. This patch does not handle any AST traversing on input yet. InstallAPI is broadly an operation that takes a series of header files that represent a single dynamic library and generates a TBD file out of it which represents all the linkable symbols and necessary attributes for statically linking in clients. It is the linkable object in all Apple SDKs and when building dylibs in Xcode. `clang -installapi` also will support verification where it compares all the information recorded for the TBD files against the already built binary, to catch possible mismatches like when a declaration is missing a definition for an exported symbol. Added: clang/include/clang/Frontend/InstallAPIOptions.h clang/include/clang/InstallAPI/Context.h clang/lib/Frontend/InstallAPIConsumer.cpp clang/lib/InstallAPI/CMakeLists.txt clang/lib/InstallAPI/Context.cpp clang/test/Driver/installapi.h clang/test/InstallAPI/installapi-basic.test Modified: clang/include/clang/Basic/DiagnosticDriverKinds.td clang/include/clang/Driver/Action.h clang/include/clang/Driver/Options.td clang/include/clang/Driver/Types.def clang/include/clang/Frontend/CompilerInstance.h clang/include/clang/Frontend/CompilerInvocation.h clang/include/clang/Frontend/FrontendActions.h clang/include/clang/Frontend/FrontendOptions.h clang/lib/CMakeLists.txt clang/lib/Driver/Action.cpp clang/lib/Driver/Driver.cpp clang/lib/Driver/ToolChain.cpp clang/lib/Driver/ToolChains/Clang.cpp clang/lib/Frontend/CMakeLists.txt clang/lib/Frontend/CompilerInvocation.cpp clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp clang/test/CMakeLists.txt clang/test/lit.cfg.py Removed: diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td index b13181f6e70894..0807d8877591a6 100644 --- a/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -804,4 +804,7 @@ def warn_android_unversioned_fallback : Warning< def err_drv_triple_version_invalid : Error< "version '%0' in target triple '%1' is invalid">; + +def err_drv_installapi_unsupported : Error< + "InstallAPI is not supported for '%0'">; } diff --git a/clang/include/clang/Driver/Action.h b/clang/include/clang/Driver/Action.h index 04fa8b01b418f8..2768e2f5df1a9e 100644 --- a/clang/include/clang/Driver/Action.h +++ b/clang/include/clang/Driver/Action.h @@ -59,6 +59,7 @@ class Action { PreprocessJobClass, PrecompileJobClass, ExtractAPIJobClass, +InstallAPIJobClass, AnalyzeJobClass, MigrateJobClass, CompileJobClass, @@ -448,6 +449,17 @@ class ExtractAPIJobAction : public JobAction { void addHeaderInput(Action *Input) { getInputs().push_back(Input); } }; +class InstallAPIJobAction : public JobAction { + void anchor() override; + +public: + InstallAPIJobAction(Action *Input, types::ID OutputType); + + static bool classof(const Action *A) { +return A->getKind() == InstallAPIJobClass; + } +}; + class AnalyzeJobAction : public JobAction { void anchor() override; diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index c625d0dd1c0c72..95b464e7d61834 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -309,6 +309,8 @@ class AnalyzerOpts : KeyPathAndMacro<"AnalyzerOpts->", base, "ANALYZER_"> {} class MigratorOpts : KeyPathAndMacro<"MigratorOpts.", base, "MIGRATOR_"> {} +class InstallAPIOpts + : KeyPathAndMacro<"InstallAPIOpts.", base, "INSTALLAPI_"> {} // A boolean option which is opt-in in CC1. The positive option exists in CC1 and // Args.hasArg(OPT_ffoo) can be used to check that the flag is enabled. @@ -1114,7 +1116,8 @@ def config_user_dir_EQ : Joined<["--"], "config-user-dir=">, def coverage : Flag<["-", "--"], "coverage">, Group, Visibility<[ClangOption, CLOption]>; def cpp_precomp : Flag<["-"], "cpp-precomp">, Group; -def current__version : JoinedOrSeparate<["-"], "current_version">; +def current__version : JoinedOrSeparate<["-"], "current_version">, + Visibility<[ClangOption,
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
https://github.com/shiltian updated https://github.com/llvm/llvm-project/pull/80908 >From 47b96d282d5416f9dd4c41013d44f8865a1a0d31 Mon Sep 17 00:00:00 2001 From: Shilei Tian Date: Tue, 13 Feb 2024 21:34:44 -0500 Subject: [PATCH] [RFC][WIP][AMDGPU] Use `bf16` instead of `i16` for bfloat Currently it looks like we generally use `i16` to represent `bf16` in those tablegen files. I'm not sure of the reason behind it. My wild guess is the type `bf16` was not available when we enabled the support. This patch is trying to use `bf16` directly in those tablegen files, aiming at fixing #79369. Of course for #79369 a workaround can be to treat all `INT16` variants as `BFloat` in `getOpFltSemantics`, but it doesn't look good IMHO. Since I'm fairly new to AMDGPU backend, I'd appreciate it if you can point out where I don't understand correctly. --- clang/lib/CodeGen/CGBuiltin.cpp | 4 -- .../builtins-amdgcn-dl-insts-gfx11.cl | 5 +- llvm/include/llvm/IR/IntrinsicsAMDGPU.td | 8 +-- .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp | 71 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp | 57 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h | 2 + .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp | 7 ++ llvm/lib/Target/AMDGPU/SIDefines.h| 7 ++ llvm/lib/Target/AMDGPU/SIInstrInfo.cpp| 15 llvm/lib/Target/AMDGPU/SIInstrInfo.td | 58 --- llvm/lib/Target/AMDGPU/SIRegisterInfo.td | 21 +- .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp| 54 ++ llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h | 16 + llvm/lib/Target/AMDGPU/VOP3Instructions.td| 2 +- .../AMDGPU/llvm.amdgcn.fdot2.bf16.bf16.ll | 51 ++--- llvm/test/MC/AMDGPU/bf16_imm.s| 8 +++ llvm/test/MC/Disassembler/AMDGPU/bf16_imm.txt | 8 +++ 17 files changed, 326 insertions(+), 68 deletions(-) create mode 100644 llvm/test/MC/AMDGPU/bf16_imm.s create mode 100644 llvm/test/MC/Disassembler/AMDGPU/bf16_imm.txt diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index ee0b7504769622..9bc60466d09be6 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -5912,8 +5912,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } -assert(ArgValue->getType()->canLosslesslyBitCastTo(PTy) && - "Must be able to losslessly bit cast to param"); // Cast vector type (e.g., v256i32) to x86_amx, this only happen // in amx intrinsics. if (PTy->isX86_AMXTy()) @@ -5943,8 +5941,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } - assert(V->getType()->canLosslesslyBitCastTo(RetTy) && - "Must be able to losslessly bit cast result type"); // Cast x86_amx to vector type (e.g., v256i32), this only happen // in amx intrinsics. if (V->getType()->isX86_AMXTy()) diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl index dc7069decaaa61..7688dfa55a78e3 100644 --- a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl @@ -11,7 +11,10 @@ typedef unsigned short __attribute__((ext_vector_type(2))) ushort2; // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 true) // CHECK: call half @llvm.amdgcn.fdot2.f16.f16(<2 x half> %v2hA, <2 x half> %v2hB, half %hC) -// CHECK: call i16 @llvm.amdgcn.fdot2.bf16.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, i16 %sC) +// CHECK: [[s1:%[0-9]+]] = bitcast <2 x i16> %v2ssA to <2 x bfloat> +// CHECK-NEXT: [[s2:%[0-9]+]] = bitcast <2 x i16> %v2ssB to <2 x bfloat> +// CHECK-NEXT: [[s3:%[0-9]+]] = bitcast i16 %sC to bfloat +// CHECK-NEXT: [[d:%[0-9]+]] = tail call bfloat @llvm.amdgcn.fdot2.bf16.bf16(<2 x bfloat> [[s1]], <2 x bfloat> [[s2]], bfloat [[s3]]) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 true) // CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 false) diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td index 202fa4e8f4ea81..6795fb7aa0edb8 100644 --- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td +++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td @@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 : def int_amdgcn_fdot2_bf16_bf16 : ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">, DefaultAttrsIntrinsic< -[llvm_i16_ty], // %r +[llvm_bfloat_ty], // %r [ - llvm_v2i16_ty, // %a - llvm_v2i16_ty, // %b - llvm_i16_ty
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -4185,9 +4185,17 @@ bool SIInstrInfo::isInlineConstant(const MachineOperand &MO, case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: return AMDGPU::isInlinableLiteralV2F16(Imm); + case AMDGPU::OPERAND_REG_IMM_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_C_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_AC_V2BF16: +return AMDGPU::isInlinableLiteralV2BF16(Imm); + case AMDGPU::OPERAND_REG_IMM_BF16: case AMDGPU::OPERAND_REG_IMM_FP16: + case AMDGPU::OPERAND_REG_IMM_BF16_DEFERRED: case AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED: + case AMDGPU::OPERAND_REG_INLINE_C_BF16: case AMDGPU::OPERAND_REG_INLINE_C_FP16: + case AMDGPU::OPERAND_REG_INLINE_AC_BF16: shiltian wrote: Okay, I copied `isInlinableLiteralBF16` from https://github.com/llvm/llvm-project/pull/81345. Initially I thought https://github.com/llvm/llvm-project/pull/81345 would be landed before this one, but I went down that rabbit hole and still didn't make it fully work. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
https://github.com/shiltian updated https://github.com/llvm/llvm-project/pull/80908 >From 22fd628687652e7f9d8795c48e9f794fdd684c45 Mon Sep 17 00:00:00 2001 From: Shilei Tian Date: Tue, 13 Feb 2024 21:27:17 -0500 Subject: [PATCH] [RFC][WIP][AMDGPU] Use `bf16` instead of `i16` for bfloat Currently it looks like we generally use `i16` to represent `bf16` in those tablegen files. I'm not sure of the reason behind it. My wild guess is the type `bf16` was not available when we enabled the support. This patch is trying to use `bf16` directly in those tablegen files, aiming at fixing #79369. Of course for #79369 a workaround can be to treat all `INT16` variants as `BFloat` in `getOpFltSemantics`, but it doesn't look good IMHO. Since I'm fairly new to AMDGPU backend, I'd appreciate it if you can point out where I don't understand correctly. --- clang/lib/CodeGen/CGBuiltin.cpp | 4 -- .../builtins-amdgcn-dl-insts-gfx11.cl | 5 +- llvm/include/llvm/IR/IntrinsicsAMDGPU.td | 8 +-- .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp | 71 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp | 57 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h | 2 + .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp | 7 ++ llvm/lib/Target/AMDGPU/SIDefines.h| 7 ++ llvm/lib/Target/AMDGPU/SIInstrInfo.cpp| 15 llvm/lib/Target/AMDGPU/SIInstrInfo.td | 58 --- llvm/lib/Target/AMDGPU/SIRegisterInfo.td | 21 +- .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp| 54 ++ llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h | 16 + llvm/lib/Target/AMDGPU/VOP3Instructions.td| 2 +- .../AMDGPU/llvm.amdgcn.fdot2.bf16.bf16.ll | 51 ++--- llvm/test/MC/AMDGPU/bf16_imm.s| 8 +++ 16 files changed, 318 insertions(+), 68 deletions(-) create mode 100644 llvm/test/MC/AMDGPU/bf16_imm.s diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index ee0b7504769622..9bc60466d09be6 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -5912,8 +5912,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } -assert(ArgValue->getType()->canLosslesslyBitCastTo(PTy) && - "Must be able to losslessly bit cast to param"); // Cast vector type (e.g., v256i32) to x86_amx, this only happen // in amx intrinsics. if (PTy->isX86_AMXTy()) @@ -5943,8 +5941,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } - assert(V->getType()->canLosslesslyBitCastTo(RetTy) && - "Must be able to losslessly bit cast result type"); // Cast x86_amx to vector type (e.g., v256i32), this only happen // in amx intrinsics. if (V->getType()->isX86_AMXTy()) diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl index dc7069decaaa61..7688dfa55a78e3 100644 --- a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl @@ -11,7 +11,10 @@ typedef unsigned short __attribute__((ext_vector_type(2))) ushort2; // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 true) // CHECK: call half @llvm.amdgcn.fdot2.f16.f16(<2 x half> %v2hA, <2 x half> %v2hB, half %hC) -// CHECK: call i16 @llvm.amdgcn.fdot2.bf16.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, i16 %sC) +// CHECK: [[s1:%[0-9]+]] = bitcast <2 x i16> %v2ssA to <2 x bfloat> +// CHECK-NEXT: [[s2:%[0-9]+]] = bitcast <2 x i16> %v2ssB to <2 x bfloat> +// CHECK-NEXT: [[s3:%[0-9]+]] = bitcast i16 %sC to bfloat +// CHECK-NEXT: [[d:%[0-9]+]] = tail call bfloat @llvm.amdgcn.fdot2.bf16.bf16(<2 x bfloat> [[s1]], <2 x bfloat> [[s2]], bfloat [[s3]]) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 true) // CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 false) diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td index 202fa4e8f4ea81..6795fb7aa0edb8 100644 --- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td +++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td @@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 : def int_amdgcn_fdot2_bf16_bf16 : ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">, DefaultAttrsIntrinsic< -[llvm_i16_ty], // %r +[llvm_bfloat_ty], // %r [ - llvm_v2i16_ty, // %a - llvm_v2i16_ty, // %b - llvm_i16_ty// %c + llvm_v2bf16_ty, // %a + llvm_v2bf16_ty, // %b + llvm_bfloat_ty// %c ], [IntrNoMem, In
[clang] [Clang][CodeGen] Loose the cast check when emitting builtins (PR #81669)
efriedma-quic wrote: I can't tell what you're trying to fix here. Is this fixing a crash? Or is the check redundant? Or is it necessary for some followup change you want to make? https://github.com/llvm/llvm-project/pull/81669 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ObjC] Defer to the LLVM backend for unaligned atomic load and stores (PR #79191)
https://github.com/AtariDreams updated https://github.com/llvm/llvm-project/pull/79191 >From 83ad8677e5e5c641505806b411216ddc8588d712 Mon Sep 17 00:00:00 2001 From: Rose <83477269+ataridre...@users.noreply.github.com> Date: Tue, 23 Jan 2024 13:59:05 -0500 Subject: [PATCH] [ObjC] Defer to the LLVM backend for unaligned atomic load and stores LLVM can codegen correctly for atomics of any alignment in IR, on any architecture (via using libcalls when necessary). So, the ObjC code's hasUnalignedAtomics can be removed. We can use copyStruct if the size is too big. --- clang/lib/CodeGen/CGObjC.cpp| 17 - clang/test/CodeGenObjC/objc_copyStruct.m| 3 +-- clang/test/CodeGenObjC/property-aggregate.m | 15 ++- 3 files changed, 3 insertions(+), 32 deletions(-) diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp index f3a948cf13f9c9..ccda7ce8f41b9f 100644 --- a/clang/lib/CodeGen/CGObjC.cpp +++ b/clang/lib/CodeGen/CGObjC.cpp @@ -842,15 +842,6 @@ static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, callee, ReturnValueSlot(), args); } -/// Determine whether the given architecture supports unaligned atomic -/// accesses. They don't have to be fast, just faster than a function -/// call and a mutex. -static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) { - // FIXME: Allow unaligned atomic load/store on x86. (It is not - // currently supported by the backend.) - return false; -} - /// Return the maximum size that permits atomic accesses for the given /// architecture. static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM, @@ -1023,14 +1014,6 @@ PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM, llvm::Triple::ArchType arch = CGM.getTarget().getTriple().getArch(); - // Most architectures require memory to fit within a single cache - // line, so the alignment has to be at least the size of the access. - // Otherwise we have to grab a lock. - if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) { -Kind = CopyStruct; -return; - } - // If the ivar's size exceeds the architecture's maximum atomic // access size, we have to use CopyStruct. if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) { diff --git a/clang/test/CodeGenObjC/objc_copyStruct.m b/clang/test/CodeGenObjC/objc_copyStruct.m index 7bbad866e2b1fb..8e52815a308abc 100644 --- a/clang/test/CodeGenObjC/objc_copyStruct.m +++ b/clang/test/CodeGenObjC/objc_copyStruct.m @@ -2,7 +2,7 @@ // RUN: %clang -target x86_64-apple-ios -fobjc-runtime=ios -Wno-objc-root-class -S -o - -emit-llvm %s | FileCheck %s struct S { - float f, g; + double f, g; }; @interface I @@ -13,4 +13,3 @@ @implementation I @end // CHECK: declare {{.*}}void @objc_copyStruct(ptr, ptr, i64, i1, i1) - diff --git a/clang/test/CodeGenObjC/property-aggregate.m b/clang/test/CodeGenObjC/property-aggregate.m index f4211b6b62bd50..4c8c8893f920f4 100644 --- a/clang/test/CodeGenObjC/property-aggregate.m +++ b/clang/test/CodeGenObjC/property-aggregate.m @@ -1,13 +1,8 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck %s -// This structure's size is not a power of two, so the property does -// not get native atomics, even though x86-64 can do unaligned atomics -// with a lock prefix. struct s3 { char c[3]; }; // This structure's size is, so it does, because it can. -// FIXME: But we don't at the moment; the backend doesn't know how to generate -// correct code. struct s4 { char c[4]; }; @interface Test0 @@ -18,14 +13,8 @@ @implementation Test0 @synthesize s3, s4; @end -// CHECK: define internal i24 @"\01-[Test0 s3]"( -// CHECK: call void @objc_copyStruct -// CHECK: define internal void @"\01-[Test0 setS3:]"( -// CHECK: call void @objc_copyStruct -// CHECK: define internal i32 @"\01-[Test0 s4]"( -// CHECK: call void @objc_copyStruct -// CHECK: define internal void @"\01-[Test0 setS4:]"( -// CHECK: call void @objc_copyStruct + NOTE: These prefixes are unused and the list is autogenerated. Do not add tests below this line: +// CHECK: {{.*}} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -4185,9 +4185,17 @@ bool SIInstrInfo::isInlineConstant(const MachineOperand &MO, case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: return AMDGPU::isInlinableLiteralV2F16(Imm); + case AMDGPU::OPERAND_REG_IMM_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_C_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_AC_V2BF16: +return AMDGPU::isInlinableLiteralV2BF16(Imm); + case AMDGPU::OPERAND_REG_IMM_BF16: case AMDGPU::OPERAND_REG_IMM_FP16: + case AMDGPU::OPERAND_REG_IMM_BF16_DEFERRED: case AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED: + case AMDGPU::OPERAND_REG_INLINE_C_BF16: case AMDGPU::OPERAND_REG_INLINE_C_FP16: + case AMDGPU::OPERAND_REG_INLINE_AC_BF16: rampitec wrote: But right in this place you know the actual format. So you can split F16 and BF16 code and call different functions. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CodeGen] Shift relink option implementation away from module cloning (PR #81693)
https://github.com/lamb-j updated https://github.com/llvm/llvm-project/pull/81693 >From aff288af78b94dbd7ef317ce368f25a305798adc Mon Sep 17 00:00:00 2001 From: Jacob Lambert Date: Tue, 13 Feb 2024 17:30:21 -0800 Subject: [PATCH 1/2] [clang][CodeGen] Shift relink option implementation away from module cloning We recently implemented a new option allowing relinking of bitcode modules via the "-mllvm -relink-builtin-bitcode-postop" option. This implementation relied on llvm::CloneModule() in order to pass copies to modules and preserve the original modules for later relinking. However, cloning modules has been found to be prohibitively expensive, significantly increasing compilation time for large bitcode libraries. In this patch, we shift the relink option implementation to instead link the original modules initially, and reload modules from the file system if relinking is requested. This approach results in significantly reduced overhead. --- clang/include/clang/Basic/FileManager.h | 4 +- clang/lib/Basic/FileManager.cpp | 2 +- clang/lib/CodeGen/BackendConsumer.h | 16 ++- clang/lib/CodeGen/CodeGenAction.cpp | 163 clang/lib/CodeGen/LinkInModulesPass.cpp | 14 +- 5 files changed, 110 insertions(+), 89 deletions(-) diff --git a/clang/include/clang/Basic/FileManager.h b/clang/include/clang/Basic/FileManager.h index 997c17a0ffcfcc..2245fd78bfc9f0 100644 --- a/clang/include/clang/Basic/FileManager.h +++ b/clang/include/clang/Basic/FileManager.h @@ -283,7 +283,7 @@ class FileManager : public RefCountedBase { bool RequiresNullTerminator = true); llvm::ErrorOr> getBufferForFile(StringRef Filename, bool isVolatile = false, - bool RequiresNullTerminator = true) { + bool RequiresNullTerminator = true) const { return getBufferForFileImpl(Filename, /*FileSize=*/-1, isVolatile, RequiresNullTerminator); } @@ -291,7 +291,7 @@ class FileManager : public RefCountedBase { private: llvm::ErrorOr> getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile, - bool RequiresNullTerminator); + bool RequiresNullTerminator) const; public: /// Get the 'stat' information for the given \p Path. diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp index 6097a27e429d66..cd520a6375e07e 100644 --- a/clang/lib/Basic/FileManager.cpp +++ b/clang/lib/Basic/FileManager.cpp @@ -547,7 +547,7 @@ FileManager::getBufferForFile(FileEntryRef FE, bool isVolatile, llvm::ErrorOr> FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile, - bool RequiresNullTerminator) { + bool RequiresNullTerminator) const { if (FileSystemOpts.WorkingDir.empty()) return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator, isVolatile); diff --git a/clang/lib/CodeGen/BackendConsumer.h b/clang/lib/CodeGen/BackendConsumer.h index 72a814cd43d738..fd0f1984d6c0f7 100644 --- a/clang/lib/CodeGen/BackendConsumer.h +++ b/clang/lib/CodeGen/BackendConsumer.h @@ -34,6 +34,7 @@ class BackendConsumer : public ASTConsumer { const CodeGenOptions &CodeGenOpts; const TargetOptions &TargetOpts; const LangOptions &LangOpts; + const FileManager &FileMgr; std::unique_ptr AsmOutStream; ASTContext *Context; IntrusiveRefCntPtr FS; @@ -74,8 +75,8 @@ class BackendConsumer : public ASTConsumer { const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, - const TargetOptions &TargetOpts, - const LangOptions &LangOpts, const std::string &InFile, + const TargetOptions &TargetOpts, const LangOptions &LangOpts, + const FileManager &FileMgr, const std::string &InFile, SmallVector LinkModules, std::unique_ptr OS, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo = nullptr); @@ -88,8 +89,8 @@ class BackendConsumer : public ASTConsumer { const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, - const TargetOptions &TargetOpts, - const LangOptions &LangOpts, llvm::Module *Module, + const TargetOptions &TargetOpts, const LangOptions &LangOpts, + const FileManager &FileMgr, llvm::Module *Module, SmallVector LinkModules, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo = nullptr); @@ -111,10 +112,13 @@ class BackendConsumer : public ASTConsumer { void AssignInheritanceModel(CXXRecordDe
[clang] [llvm] MIPS/clang: Fix asm constraint for softfloat (PR #79116)
brad0 wrote: @wzssyqa Ping. https://github.com/llvm/llvm-project/pull/79116 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CodeGen] Shift relink option implementation away from module cloning (PR #81693)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Jacob Lambert (lamb-j) Changes We recently implemented a new option allowing relinking of bitcode modules via the "-mllvm -relink-builtin-bitcode-postop" option. This implementation relied on llvm::CloneModule() in order to pass copies to modules and preserve the original modules for later relinking. However, cloning modules has been found to be prohibitively expensive, significantly increasing compilation time for large bitcode libraries. In this patch, we shift the relink option implementation to instead link the original modules initially, and reload modules from the file system if relinking is requested. This approach results in significantly reduced overhead. --- Full diff: https://github.com/llvm/llvm-project/pull/81693.diff 5 Files Affected: - (modified) clang/include/clang/Basic/FileManager.h (+2-2) - (modified) clang/lib/Basic/FileManager.cpp (+1-1) - (modified) clang/lib/CodeGen/BackendConsumer.h (+10-6) - (modified) clang/lib/CodeGen/CodeGenAction.cpp (+85-78) - (modified) clang/lib/CodeGen/LinkInModulesPass.cpp (+12-2) ``diff diff --git a/clang/include/clang/Basic/FileManager.h b/clang/include/clang/Basic/FileManager.h index 997c17a0ffcfcc..2245fd78bfc9f0 100644 --- a/clang/include/clang/Basic/FileManager.h +++ b/clang/include/clang/Basic/FileManager.h @@ -283,7 +283,7 @@ class FileManager : public RefCountedBase { bool RequiresNullTerminator = true); llvm::ErrorOr> getBufferForFile(StringRef Filename, bool isVolatile = false, - bool RequiresNullTerminator = true) { + bool RequiresNullTerminator = true) const { return getBufferForFileImpl(Filename, /*FileSize=*/-1, isVolatile, RequiresNullTerminator); } @@ -291,7 +291,7 @@ class FileManager : public RefCountedBase { private: llvm::ErrorOr> getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile, - bool RequiresNullTerminator); + bool RequiresNullTerminator) const; public: /// Get the 'stat' information for the given \p Path. diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp index 6097a27e429d66..cd520a6375e07e 100644 --- a/clang/lib/Basic/FileManager.cpp +++ b/clang/lib/Basic/FileManager.cpp @@ -547,7 +547,7 @@ FileManager::getBufferForFile(FileEntryRef FE, bool isVolatile, llvm::ErrorOr> FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile, - bool RequiresNullTerminator) { + bool RequiresNullTerminator) const { if (FileSystemOpts.WorkingDir.empty()) return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator, isVolatile); diff --git a/clang/lib/CodeGen/BackendConsumer.h b/clang/lib/CodeGen/BackendConsumer.h index 72a814cd43d738..fd0f1984d6c0f7 100644 --- a/clang/lib/CodeGen/BackendConsumer.h +++ b/clang/lib/CodeGen/BackendConsumer.h @@ -34,6 +34,7 @@ class BackendConsumer : public ASTConsumer { const CodeGenOptions &CodeGenOpts; const TargetOptions &TargetOpts; const LangOptions &LangOpts; + const FileManager &FileMgr; std::unique_ptr AsmOutStream; ASTContext *Context; IntrusiveRefCntPtr FS; @@ -74,8 +75,8 @@ class BackendConsumer : public ASTConsumer { const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, - const TargetOptions &TargetOpts, - const LangOptions &LangOpts, const std::string &InFile, + const TargetOptions &TargetOpts, const LangOptions &LangOpts, + const FileManager &FileMgr, const std::string &InFile, SmallVector LinkModules, std::unique_ptr OS, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo = nullptr); @@ -88,8 +89,8 @@ class BackendConsumer : public ASTConsumer { const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, - const TargetOptions &TargetOpts, - const LangOptions &LangOpts, llvm::Module *Module, + const TargetOptions &TargetOpts, const LangOptions &LangOpts, + const FileManager &FileMgr, llvm::Module *Module, SmallVector LinkModules, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo = nullptr); @@ -111,10 +112,13 @@ class BackendConsumer : public ASTConsumer { void AssignInheritanceModel(CXXRecordDecl *RD) override; void HandleVTable(CXXRecordDecl *RD) override; - - // Links each entry in LinkModules into our module. Returns true on error. +
[clang] [clang][CodeGen] Shift relink option implementation away from module cloning (PR #81693)
https://github.com/lamb-j created https://github.com/llvm/llvm-project/pull/81693 We recently implemented a new option allowing relinking of bitcode modules via the "-mllvm -relink-builtin-bitcode-postop" option. This implementation relied on llvm::CloneModule() in order to pass copies to modules and preserve the original modules for later relinking. However, cloning modules has been found to be prohibitively expensive, significantly increasing compilation time for large bitcode libraries. In this patch, we shift the relink option implementation to instead link the original modules initially, and reload modules from the file system if relinking is requested. This approach results in significantly reduced overhead. >From aff288af78b94dbd7ef317ce368f25a305798adc Mon Sep 17 00:00:00 2001 From: Jacob Lambert Date: Tue, 13 Feb 2024 17:30:21 -0800 Subject: [PATCH] [clang][CodeGen] Shift relink option implementation away from module cloning We recently implemented a new option allowing relinking of bitcode modules via the "-mllvm -relink-builtin-bitcode-postop" option. This implementation relied on llvm::CloneModule() in order to pass copies to modules and preserve the original modules for later relinking. However, cloning modules has been found to be prohibitively expensive, significantly increasing compilation time for large bitcode libraries. In this patch, we shift the relink option implementation to instead link the original modules initially, and reload modules from the file system if relinking is requested. This approach results in significantly reduced overhead. --- clang/include/clang/Basic/FileManager.h | 4 +- clang/lib/Basic/FileManager.cpp | 2 +- clang/lib/CodeGen/BackendConsumer.h | 16 ++- clang/lib/CodeGen/CodeGenAction.cpp | 163 clang/lib/CodeGen/LinkInModulesPass.cpp | 14 +- 5 files changed, 110 insertions(+), 89 deletions(-) diff --git a/clang/include/clang/Basic/FileManager.h b/clang/include/clang/Basic/FileManager.h index 997c17a0ffcfcc..2245fd78bfc9f0 100644 --- a/clang/include/clang/Basic/FileManager.h +++ b/clang/include/clang/Basic/FileManager.h @@ -283,7 +283,7 @@ class FileManager : public RefCountedBase { bool RequiresNullTerminator = true); llvm::ErrorOr> getBufferForFile(StringRef Filename, bool isVolatile = false, - bool RequiresNullTerminator = true) { + bool RequiresNullTerminator = true) const { return getBufferForFileImpl(Filename, /*FileSize=*/-1, isVolatile, RequiresNullTerminator); } @@ -291,7 +291,7 @@ class FileManager : public RefCountedBase { private: llvm::ErrorOr> getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile, - bool RequiresNullTerminator); + bool RequiresNullTerminator) const; public: /// Get the 'stat' information for the given \p Path. diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp index 6097a27e429d66..cd520a6375e07e 100644 --- a/clang/lib/Basic/FileManager.cpp +++ b/clang/lib/Basic/FileManager.cpp @@ -547,7 +547,7 @@ FileManager::getBufferForFile(FileEntryRef FE, bool isVolatile, llvm::ErrorOr> FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile, - bool RequiresNullTerminator) { + bool RequiresNullTerminator) const { if (FileSystemOpts.WorkingDir.empty()) return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator, isVolatile); diff --git a/clang/lib/CodeGen/BackendConsumer.h b/clang/lib/CodeGen/BackendConsumer.h index 72a814cd43d738..fd0f1984d6c0f7 100644 --- a/clang/lib/CodeGen/BackendConsumer.h +++ b/clang/lib/CodeGen/BackendConsumer.h @@ -34,6 +34,7 @@ class BackendConsumer : public ASTConsumer { const CodeGenOptions &CodeGenOpts; const TargetOptions &TargetOpts; const LangOptions &LangOpts; + const FileManager &FileMgr; std::unique_ptr AsmOutStream; ASTContext *Context; IntrusiveRefCntPtr FS; @@ -74,8 +75,8 @@ class BackendConsumer : public ASTConsumer { const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, - const TargetOptions &TargetOpts, - const LangOptions &LangOpts, const std::string &InFile, + const TargetOptions &TargetOpts, const LangOptions &LangOpts, + const FileManager &FileMgr, const std::string &InFile, SmallVector LinkModules, std::unique_ptr OS, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo = nullptr); @@ -88,8 +89,8 @@ class BackendConsumer : public ASTConsumer { const HeaderSearchO
[clang] [llvm] [MC/DC] Refactor: Let MCDCConditionID int16_t with zero-origin (PR #81257)
https://github.com/chapuni updated https://github.com/llvm/llvm-project/pull/81257 >From b2e8b3eaa067844a5fa5643aca17dbb0f237182e Mon Sep 17 00:00:00 2001 From: NAKAMURA Takumi Date: Sat, 10 Feb 2024 00:08:36 +0900 Subject: [PATCH 1/2] [MC/DC] Refactor: Let MCDCConditionID int16_t with zero-origin Also, Let NumConditions uint16_t --- clang/lib/CodeGen/CodeGenPGO.cpp | 8 ++--- clang/lib/CodeGen/CodeGenPGO.h| 2 +- clang/lib/CodeGen/CoverageMappingGen.cpp | 30 +-- clang/lib/CodeGen/CoverageMappingGen.h| 4 +-- .../ProfileData/Coverage/CoverageMapping.h| 10 +++ .../ProfileData/Coverage/CoverageMapping.cpp | 25 .../Coverage/CoverageMappingReader.cpp| 17 ++- .../Coverage/CoverageMappingWriter.cpp| 6 ++-- .../ProfileData/CoverageMappingTest.cpp | 18 +-- 9 files changed, 61 insertions(+), 59 deletions(-) diff --git a/clang/lib/CodeGen/CodeGenPGO.cpp b/clang/lib/CodeGen/CodeGenPGO.cpp index 5d7c3847745762..9025889f443b88 100644 --- a/clang/lib/CodeGen/CodeGenPGO.cpp +++ b/clang/lib/CodeGen/CodeGenPGO.cpp @@ -1033,7 +1033,7 @@ void CodeGenPGO::emitCounterRegionMapping(const Decl *D) { std::string CoverageMapping; llvm::raw_string_ostream OS(CoverageMapping); - RegionCondIDMap.reset(new llvm::DenseMap); + RegionCondIDMap.reset(new llvm::DenseMap); CoverageMappingGen MappingGen( *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(), CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCBitmapMap.get(), @@ -1198,8 +1198,8 @@ void CodeGenPGO::emitMCDCCondBitmapUpdate(CGBuilderTy &Builder, const Expr *S, return; // Extract the ID of the condition we are setting in the bitmap. - unsigned CondID = ExprMCDCConditionIDMapIterator->second; - assert(CondID > 0 && "Condition has no ID!"); + auto CondID = ExprMCDCConditionIDMapIterator->second; + assert(CondID >= 0 && "Condition has no ID!"); auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext()); @@ -1208,7 +1208,7 @@ void CodeGenPGO::emitMCDCCondBitmapUpdate(CGBuilderTy &Builder, const Expr *S, // the resulting value is used to update the boolean expression's bitmap. llvm::Value *Args[5] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), Builder.getInt64(FunctionHash), - Builder.getInt32(CondID - 1), + Builder.getInt32(CondID), MCDCCondBitmapAddr.getPointer(), Val}; Builder.CreateCall( CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_condbitmap_update), diff --git a/clang/lib/CodeGen/CodeGenPGO.h b/clang/lib/CodeGen/CodeGenPGO.h index 6596b6c3527764..5f2941cfb2e95e 100644 --- a/clang/lib/CodeGen/CodeGenPGO.h +++ b/clang/lib/CodeGen/CodeGenPGO.h @@ -37,7 +37,7 @@ class CodeGenPGO { uint64_t FunctionHash; std::unique_ptr> RegionCounterMap; std::unique_ptr> RegionMCDCBitmapMap; - std::unique_ptr> RegionCondIDMap; + std::unique_ptr> RegionCondIDMap; std::unique_ptr> StmtCountMap; std::unique_ptr ProfRecord; std::vector RegionCounts; diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp b/clang/lib/CodeGen/CoverageMappingGen.cpp index 0c43317642bca4..d918acd951dd8c 100644 --- a/clang/lib/CodeGen/CoverageMappingGen.cpp +++ b/clang/lib/CodeGen/CoverageMappingGen.cpp @@ -587,8 +587,8 @@ struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { struct MCDCCoverageBuilder { struct DecisionIDPair { -MCDCConditionID TrueID = 0; -MCDCConditionID FalseID = 0; +MCDCConditionID TrueID = -1; +MCDCConditionID FalseID = -1; }; /// The AST walk recursively visits nested logical-AND or logical-OR binary @@ -684,11 +684,11 @@ struct MCDCCoverageBuilder { llvm::SmallVector DecisionStack; llvm::DenseMap &CondIDs; llvm::DenseMap &MCDCBitmapMap; - MCDCConditionID NextID = 1; + MCDCConditionID NextID = 0; bool NotMapped = false; /// Represent a sentinel value of [0,0] for the bottom of DecisionStack. - static constexpr DecisionIDPair DecisionStackSentinel{0, 0}; + static constexpr DecisionIDPair DecisionStackSentinel{-1, -1}; /// Is this a logical-AND operation? bool isLAnd(const BinaryOperator *E) const { @@ -705,12 +705,12 @@ struct MCDCCoverageBuilder { /// Return whether the build of the control flow map is at the top-level /// (root) of a logical operator nest in a boolean expression prior to the /// assignment of condition IDs. - bool isIdle() const { return (NextID == 1 && !NotMapped); } + bool isIdle() const { return (NextID == 0 && !NotMapped); } /// Return whether any IDs have been assigned in the build of the control /// flow map, indicating that the map is being generated for this boolean /// expression. - bool isBuilding() const { return (NextID > 1); } + bool isBuilding() const { return (NextID > 0); } /// Set the given condition's ID.
[clang] [llvm] [transforms] Inline simple variadic functions (PR #81058)
jdoerfert wrote: High level question: Does this patch eliminate the variadic call edge, or, does it perform inlining on very special variadic function definitions? I thought the former but `isFunctionInlinable`, sufficiently confused me. https://github.com/llvm/llvm-project/pull/81058 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [RISCV] Add canonical ISA string as Module metadata in IR. (PR #80760)
https://github.com/topperc closed https://github.com/llvm/llvm-project/pull/80760 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] f45b9d9 - [RISCV] Add canonical ISA string as Module metadata in IR. (#80760)
Author: Craig Topper Date: 2024-02-13T16:17:50-08:00 New Revision: f45b9d987dfc5904d4129aa006ab20614b3174e3 URL: https://github.com/llvm/llvm-project/commit/f45b9d987dfc5904d4129aa006ab20614b3174e3 DIFF: https://github.com/llvm/llvm-project/commit/f45b9d987dfc5904d4129aa006ab20614b3174e3.diff LOG: [RISCV] Add canonical ISA string as Module metadata in IR. (#80760) In an LTO build, we don't set the ELF attributes to indicate what extensions were compiled with. The target CPU/Attrs in RISCVTargetMachine do not get set for an LTO build. Each function gets a target-cpu/feature attribute, but this isn't usable to set ELF attributs since we wouldn't know what function to use. We can't just once since it might have been compiler with an attribute likes target_verson. This patch adds the ISA as Module metadata so we can retrieve it in the backend. Individual translation units can still be compiled with different strings so we need to collect the unique set when Modules are merged. The backend will need to combine the unique ISA strings to produce a single value for the ELF attributes. This will be done in a separate patch. Added: clang/test/CodeGen/RISCV/riscv-metadata-arch.c Modified: clang/lib/CodeGen/CodeGenModule.cpp clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c Removed: diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 2f923d5457f9cf..c984260b082cd1 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -68,6 +68,7 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/RISCVISAInfo.h" #include "llvm/Support/TimeProfiler.h" #include "llvm/Support/xxhash.h" #include "llvm/TargetParser/Triple.h" @@ -1057,6 +1058,19 @@ void CodeGenModule::Release() { llvm::LLVMContext &Ctx = TheModule.getContext(); getModule().addModuleFlag(llvm::Module::Error, "target-abi", llvm::MDString::get(Ctx, ABIStr)); + +// Add the canonical ISA string as metadata so the backend can set the ELF +// attributes correctly. We use AppendUnique so LTO will keep all of the +// unique ISA strings that were linked together. +const std::vector &Features = +getTarget().getTargetOpts().Features; +auto ParseResult = +llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features); +if (!errorToBool(ParseResult.takeError())) + getModule().addModuleFlag( + llvm::Module::AppendUnique, "riscv-isa", + llvm::MDNode::get( + Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString(; } if (CodeGenOpts.SanitizeCfiCrossDso) { diff --git a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c index 897edbc6450af6..b11c2ca010e7ce 100644 --- a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c +++ b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c @@ -28,190 +28,190 @@ vint8m1_t *scvc1, *scvc2; // clang-format off void ntl_all_sizes() { // CHECK-LABEL: ntl_all_sizes - uc = __riscv_ntl_load(&sc, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5 - sc = __riscv_ntl_load(&uc, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5 - us = __riscv_ntl_load(&ss, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5 - ss = __riscv_ntl_load(&us, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5 - ui = __riscv_ntl_load(&si, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5 - si = __riscv_ntl_load(&ui, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5 - ull = __riscv_ntl_load(&sll, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5 - sll = __riscv_ntl_load(&ull, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5 - h1 = __riscv_ntl_load(&h2, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load half{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5 - f1 = __riscv_ntl_load(&f2, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load float{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5 - d1 = __riscv_ntl_load(&d2, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load double{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5 - v4si1 = __riscv_ntl_load(&v4si2, __RISCV_NTLH_INNERMOST_PRIVATE
[clang] [compiler-rt] [asan][windows] Eliminate the static asan runtime on windows (PR #81677)
https://github.com/vitalybuka commented: This is long description, but it does not explain WHY. Could you please add some explanation there? https://github.com/llvm/llvm-project/pull/81677 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [asan][windows] Eliminate the static asan runtime on windows (PR #81677)
vitalybuka wrote: Added know some folks who may know how Asan in used by Chromium on Windows. https://github.com/llvm/llvm-project/pull/81677 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [-Wunsafe-buffer-usage] Fixits for unsafe arguments of function pointer calls (PR #80358)
@@ -282,8 +282,8 @@ isInUnspecifiedPointerContext(internal::Matcher InnerMatcher) { //(i.e., computing the distance between two pointers); or ... auto CallArgMatcher = - callExpr(forEachArgumentWithParam(InnerMatcher, - hasPointerType() /* array also decays to pointer type*/), + callExpr(forEachArgumentWithParamType(InnerMatcher, + isAnyPointer() /* array also decays to pointer type*/), haoNoQ wrote: Yeah but I mean, does the new code handle typedefs correctly? That's probably why `hasCanonicalType()` was there in the first place, to handle things like typedefs. https://github.com/llvm/llvm-project/pull/80358 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [CMake][PGO] Build Sema.cpp to generate profdata for PGO builds (PR #77347)
@@ -26,9 +30,23 @@ if(LLVM_BUILD_INSTRUMENTED) message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to llvm-profdata") else() add_custom_target(generate-profdata - COMMAND "${Python3_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} ${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR} + COMMAND "${Python3_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} ${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_BINARY_DIR}/profiles/ COMMENT "Merging profdata" DEPENDS generate-profraw) +if (CLANG_PGO_TRAINING_DATA_SOURCE_DIR) + llvm_ExternalProject_Add(generate-profraw-external ${CLANG_PGO_TRAINING_DATA_SOURCE_DIR} + USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS generate-profraw) + add_dependencies(generate-profdata generate-profraw-external) +else() + # Default to compiling a file from clang. This also builds all the + # dependencies needed to build this file, like TableGen. + set(generate_profraw_clang_sema tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/Sema.cpp.o) + llvm_ExternalProject_Add(generate-profraw-clang ${CMAKE_CURRENT_SOURCE_DIR}/../../../llvm + USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS generate-profraw + EXTRA_TARGETS generate_profraw_clang_sema tstellar wrote: I was compiling just a single file (SemaChecking.cpp). https://github.com/llvm/llvm-project/pull/77347 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
https://github.com/shiltian updated https://github.com/llvm/llvm-project/pull/80908 >From d72bf8bb9d1091ba76e17bf09b0aad9073e18caa Mon Sep 17 00:00:00 2001 From: Shilei Tian Date: Tue, 13 Feb 2024 19:02:41 -0500 Subject: [PATCH] [RFC][WIP][AMDGPU] Use `bf16` instead of `i16` for bfloat Currently it looks like we generally use `i16` to represent `bf16` in those tablegen files. I'm not sure of the reason behind it. My wild guess is the type `bf16` was not available when we enabled the support. This patch is trying to use `bf16` directly in those tablegen files, aiming at fixing #79369. Of course for #79369 a workaround can be to treat all `INT16` variants as `BFloat` in `getOpFltSemantics`, but it doesn't look good IMHO. Since I'm fairly new to AMDGPU backend, I'd appreciate it if you can point out where I don't understand correctly. --- clang/lib/CodeGen/CGBuiltin.cpp | 4 -- .../builtins-amdgcn-dl-insts-gfx11.cl | 5 +- llvm/include/llvm/IR/IntrinsicsAMDGPU.td | 8 +-- .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp | 71 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp | 57 +++ .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h | 2 + .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp | 7 ++ llvm/lib/Target/AMDGPU/SIDefines.h| 7 ++ llvm/lib/Target/AMDGPU/SIInstrInfo.cpp| 8 +++ llvm/lib/Target/AMDGPU/SIInstrInfo.td | 58 --- llvm/lib/Target/AMDGPU/SIRegisterInfo.td | 21 +- .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp| 37 ++ llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h | 15 llvm/lib/Target/AMDGPU/VOP3Instructions.td| 2 +- .../AMDGPU/llvm.amdgcn.fdot2.bf16.bf16.ll | 51 ++--- llvm/test/MC/AMDGPU/bf16_imm.s| 8 +++ 16 files changed, 293 insertions(+), 68 deletions(-) create mode 100644 llvm/test/MC/AMDGPU/bf16_imm.s diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index ee0b7504769622..9bc60466d09be6 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -5912,8 +5912,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } -assert(ArgValue->getType()->canLosslesslyBitCastTo(PTy) && - "Must be able to losslessly bit cast to param"); // Cast vector type (e.g., v256i32) to x86_amx, this only happen // in amx intrinsics. if (PTy->isX86_AMXTy()) @@ -5943,8 +5941,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } } - assert(V->getType()->canLosslesslyBitCastTo(RetTy) && - "Must be able to losslessly bit cast result type"); // Cast x86_amx to vector type (e.g., v256i32), this only happen // in amx intrinsics. if (V->getType()->isX86_AMXTy()) diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl index dc7069decaaa61..7688dfa55a78e3 100644 --- a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl @@ -11,7 +11,10 @@ typedef unsigned short __attribute__((ext_vector_type(2))) ushort2; // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 true) // CHECK: call half @llvm.amdgcn.fdot2.f16.f16(<2 x half> %v2hA, <2 x half> %v2hB, half %hC) -// CHECK: call i16 @llvm.amdgcn.fdot2.bf16.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, i16 %sC) +// CHECK: [[s1:%[0-9]+]] = bitcast <2 x i16> %v2ssA to <2 x bfloat> +// CHECK-NEXT: [[s2:%[0-9]+]] = bitcast <2 x i16> %v2ssB to <2 x bfloat> +// CHECK-NEXT: [[s3:%[0-9]+]] = bitcast i16 %sC to bfloat +// CHECK-NEXT: [[d:%[0-9]+]] = tail call bfloat @llvm.amdgcn.fdot2.bf16.bf16(<2 x bfloat> [[s1]], <2 x bfloat> [[s2]], bfloat [[s3]]) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 false) // CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> %v2ssB, float %fC, i1 true) // CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 false) diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td index 202fa4e8f4ea81..6795fb7aa0edb8 100644 --- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td +++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td @@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 : def int_amdgcn_fdot2_bf16_bf16 : ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">, DefaultAttrsIntrinsic< -[llvm_i16_ty], // %r +[llvm_bfloat_ty], // %r [ - llvm_v2i16_ty, // %a - llvm_v2i16_ty, // %b - llvm_i16_ty// %c + llvm_v2bf16_ty, // %a + llvm_v2bf16_ty, // %b + llvm_bfloat_ty// %c ], [IntrNoMem, IntrSpec
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -4185,9 +4185,17 @@ bool SIInstrInfo::isInlineConstant(const MachineOperand &MO, case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: return AMDGPU::isInlinableLiteralV2F16(Imm); + case AMDGPU::OPERAND_REG_IMM_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_C_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_AC_V2BF16: +return AMDGPU::isInlinableLiteralV2BF16(Imm); + case AMDGPU::OPERAND_REG_IMM_BF16: case AMDGPU::OPERAND_REG_IMM_FP16: + case AMDGPU::OPERAND_REG_IMM_BF16_DEFERRED: case AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED: + case AMDGPU::OPERAND_REG_INLINE_C_BF16: case AMDGPU::OPERAND_REG_INLINE_C_FP16: + case AMDGPU::OPERAND_REG_INLINE_AC_BF16: shiltian wrote: Yes, `isInlinableLiteral16` can't because it can't tell `fp16` and `bf16` apart by just looking at the value. That's the reason I tried really hard to get rid of `isInlinableLiteral16` in #81345 and favors the explicit version. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add `intrin0.h` header to mimic `intrin0.h` used by MSVC STL for clang-cl (PR #75711)
MaxEW707 wrote: Ping Wondering if there is anything else required of me to progress this PR forward. Let me know :). https://github.com/llvm/llvm-project/pull/75711 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -488,6 +488,49 @@ static bool printImmediateFloat16(uint32_t Imm, const MCSubtargetInfo &STI, return true; } +static bool printImmediateBFloat16(uint32_t Imm, const MCSubtargetInfo &STI, + raw_ostream &O) { + if (Imm == 0x3F80) +O << "1.0"; + else if (Imm == 0xBF80) +O << "-1.0"; + else if (Imm == 0x3F00) +O << "0.5"; + else if (Imm == 0xBF00) +O << "-0.5"; + else if (Imm == 0x4000) +O << "2.0"; + else if (Imm == 0xC000) +O << "-2.0"; + else if (Imm == 0x4080) +O << "4.0"; + else if (Imm == 0xC080) +O << "-4.0"; + else if (Imm == 0x3E22 && STI.hasFeature(AMDGPU::FeatureInv2PiInlineImm)) +O << "0.15915494"; + else +return false; + + return true; +} + +void AMDGPUInstPrinter::printImmediateBF16(uint32_t Imm, + const MCSubtargetInfo &STI, + raw_ostream &O) { + int16_t SImm = static_cast(Imm); + if (isInlinableIntLiteral(SImm)) { +O << SImm; +return; + } + + uint16_t HImm = static_cast(Imm); + if (printImmediateBFloat16(HImm, STI, O)) +return; + + uint64_t Imm16 = static_cast(Imm); shiltian wrote: Yeah, but it is to make the type promoted to `uint64_t` w/o any ambiguity. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Detect a return value of Ref & RefPtr (PR #81580)
@@ -118,6 +118,26 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F) { || FunctionName == "Identifier"; } +bool isReturnValueRefCounted(const clang::FunctionDecl *F) { + assert(F); + auto *type = F->getReturnType().getTypePtrOrNull(); + while (type) { +if (auto *elaboratedT = dyn_cast(type)) { + type = elaboratedT->desugar().getTypePtrOrNull(); + continue; +} +if (auto *specialT = dyn_cast(type)) { haoNoQ wrote: `.getTypePtrOrNull()` can be dropped here as well: ```suggestion QualType type = F->getReturnType(); while (!type.isNull()) { if (auto *elaboratedT = type->getAs()) { type = elaboratedT->desugar(); continue; } if (auto *specialT = type->getAs()) { ``` https://github.com/llvm/llvm-project/pull/81580 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -122,6 +122,26 @@ Non-comprehensive list of changes in this release New Compiler Flags -- +- ``-fsanitize=implicit-unsigned-bitfield-truncation`` catches implicit + unsigned conversions involving bitfields. +- ``-fsanitize=implicit-signed-bitfield-truncation`` catches implicit + signed conversions involving bitfields. +- ``-fsanitize=implicit-bitfield-sign-change`` catches implicit + conversions involving bitfields that result in a sign change. +- ``-fsanitize=implicit-bitfield-truncation`` a group to include both + ``-fsanitize=implicit-unsigned-bitfield-truncation`` and + ``-fsanitize=implicit-signed-bitfield-truncation``. +- ``-fsanitize=implicit-bitfield-arithmetic-value-change`` a group to + include both ``implicit-signed-bitfield-truncation`` and + ``implicit-bitfield-sign-change``. +- ``-fsanitize=implicit-bitfield-conversion`` a group to include + ``-fsanitize=implicit-unsigned-bitfield-truncation``, + ``-fsanitize=implicit-signed-bitfield-truncation`` and + ``implicit-bitfield-sign-change``. +- ``-fsanitize=implicit-integer-conversion`` a group to include + ``-fsanitize=implicit-unsigned-integer-truncation``, + ``-fsanitize=implicit-signed-integer-truncation`` and + ``implicit-integer-sign-change``. rjmccall wrote: Do we really need a million different flags here? The reason we have different checks for different signednesses with the normal conversion checks, I think, is because the standard actually treats them differently: some of those checks are actually checking for UB. Since there's no UB here in any case, I think you may be overthinking this. Consider just having `-fsanitize=implicit-bitfield-conversion`, which covers every case in which the value we'd read out the bitfield is not the value that we assigned into it. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
https://github.com/rjmccall commented: You should handle compound assignments. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -5570,11 +5570,44 @@ LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { break; } -RValue RV = EmitAnyExpr(E->getRHS()); +llvm::Value *Previous = nullptr; +RValue RV; +QualType SrcType = E->getRHS()->getType(); +// If LHS refers to a bitfield we want to retrieve the value before +// implicit conversion between the bitfield type and the RHS type +// and evaluate RHS without integer sanitizer checks (if passed) +if (auto *ICE = RetrieveImplicitCastExprForBitfieldSanitizer(E)) { rjmccall wrote: When we say "conversion between A and B", it typically means A is being converted to B, but I think you're actually talking about the reverse here. Please pull the basic conditions for whether to emit this check into this function (LHS is a bit-field + the sanitizer option); it will make the data flow much clearer. You can just evaluate them once and then check it again below. Please test for a bit-field LHS before checking for the sanitizer option. The function call here should be something like `getOriginalRHSForBitfieldSanitizer`. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -1097,6 +1112,27 @@ void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, {Src, Dst}); } +static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType, + const char *Name, + CGBuilderTy &Builder) { + // NOTE: zero value is considered to be non-negative. rjmccall wrote: This is self-evident and does not need to be in a comment. Actually, most of the comments in this function are pretty unnecessary; you can just say something like "If the type is unsigned, the value is never negative." and leave everything else self-documenting. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -324,6 +326,19 @@ class ScalarExprEmitter void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst, QualType DstType, SourceLocation Loc); + /// Emit a check that an [implicit] truncation of a bitfield does not + /// discard any bits. It is not UB, so we use the value after truncation. rjmccall wrote: The last sentence of the comment seems out of place here (and on the next function). https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -5570,11 +5570,44 @@ LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { break; } -RValue RV = EmitAnyExpr(E->getRHS()); +llvm::Value *Previous = nullptr; +RValue RV; +QualType SrcType = E->getRHS()->getType(); +// If LHS refers to a bitfield we want to retrieve the value before +// implicit conversion between the bitfield type and the RHS type +// and evaluate RHS without integer sanitizer checks (if passed) +if (auto *ICE = RetrieveImplicitCastExprForBitfieldSanitizer(E)) { + SrcType = ICE->getSubExpr()->getType(); + Previous = EmitScalarExpr(ICE->getSubExpr()); + // Pass default ScalarConversionOpts so that sanitizer check is + // not emitted here + llvm::Value *RHS = EmitScalarConversion(Previous, SrcType, ICE->getType(), + ICE->getExprLoc()); + RV = RValue::get(RHS); +} + +if (!Previous) + RV = EmitAnyExpr(E->getRHS()); + LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); + if (RV.isScalar()) EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc()); -EmitStoreThroughLValue(RV, LV); + +// Passing a pointer EmitStoreThroughBitfieldLValue will emit the result +// If sanitizer checks are not used, we do not use the result +// Hence, use EmitStoreThroughLValue instead +if (SanOpts.hasOneOf(SanitizerKind::ImplicitBitfieldConversion) && +LV.isBitField() && RV.isScalar()) { rjmccall wrote: Integer types always use scalar emission. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -1097,6 +1112,27 @@ void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, {Src, Dst}); } +static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType, + const char *Name, + CGBuilderTy &Builder) { + // NOTE: zero value is considered to be non-negative. + // Is this value a signed type? + bool VSigned = VType->isSignedIntegerOrEnumerationType(); + llvm::Type *VTy = V->getType(); + if (!VSigned) { +// If the value is unsigned, then it is never negative. +// FIXME: can we encounter non-scalar VTy here? rjmccall wrote: No, you cannot. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -1239,6 +1257,228 @@ void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, {Src, Dst}); } +// Should be called within CodeGenFunction::SanitizerScope RAII scope. +// Returns 'i1 false' when the truncation Src -> Dst was lossy. +static std::pair> +EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, + QualType DstType, CGBuilderTy &Builder) { + + llvm::Type *SrcTy = Src->getType(); + llvm::Type *DstTy = Dst->getType(); + (void)SrcTy; // Only used in assert() + (void)DstTy; // Only used in assert() rjmccall wrote: Then you should surround these variables with `#ifndef NDEBUG`. But mostly you don't need to do this; `CreateIntCast` will assert this for you. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
@@ -1035,7 +1050,7 @@ EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, } llvm::Value *Check = nullptr; - // 1. Extend the truncated value back to the same width as the Src. + // 1. Convert the Dst back to the same type as Src. rjmccall wrote: This is not an improvement in the comment. https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)
https://github.com/rjmccall edited https://github.com/llvm/llvm-project/pull/75481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
JustinStitt wrote: > UBSan is documented clang/docs/UndefinedBehaviorSanitizer.rst > https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html > > Please make sure to update the list [of available > checks](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks). > > Please also update the release notes to mention this feature. > clang/docs/ReleaseNotes.rst > Gotcha, done in [e15b6e6](https://github.com/llvm/llvm-project/pull/80089/commits/e15b6e636c27d00a4ef8d0a0f8f648bdcf11d44b) and [b978be6](https://github.com/llvm/llvm-project/pull/80089/commits/b978be62ca2d841d82924b702e8ab2b865754227). https://github.com/llvm/llvm-project/pull/80089 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 : def int_amdgcn_fdot2_bf16_bf16 : ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">, DefaultAttrsIntrinsic< -[llvm_i16_ty], // %r +[llvm_bfloat_ty], // %r shiltian wrote: The cast will be inserted automatically in `clang/lib/CodeGen/CGBuiltin.cpp` after removing the two assertions. I reverted my change to the test case by accident. Lol https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
https://github.com/JustinStitt updated https://github.com/llvm/llvm-project/pull/80089 >From 7774e4036ac1de7fdf5fe4c6b3208b492853ffc5 Mon Sep 17 00:00:00 2001 From: Justin Stitt Date: Tue, 23 Jan 2024 23:28:42 + Subject: [PATCH 01/10] add signed-integer-wrap sanitizer --- clang/include/clang/Basic/Sanitizers.def | 5 +- clang/lib/CodeGen/CGExprScalar.cpp | 62 +++- compiler-rt/lib/ubsan/ubsan_checks.inc | 2 + 3 files changed, 54 insertions(+), 15 deletions(-) diff --git a/clang/include/clang/Basic/Sanitizers.def b/clang/include/clang/Basic/Sanitizers.def index c2137e3f61f645..b987b26f93c39a 100644 --- a/clang/include/clang/Basic/Sanitizers.def +++ b/clang/include/clang/Basic/Sanitizers.def @@ -104,6 +104,7 @@ SANITIZER("shift-base", ShiftBase) SANITIZER("shift-exponent", ShiftExponent) SANITIZER_GROUP("shift", Shift, ShiftBase | ShiftExponent) SANITIZER("signed-integer-overflow", SignedIntegerOverflow) +SANITIZER("signed-integer-wrap", SignedIntegerWrap) SANITIZER("unreachable", Unreachable) SANITIZER("vla-bound", VLABound) SANITIZER("vptr", Vptr) @@ -144,7 +145,7 @@ SANITIZER_GROUP("undefined", Undefined, IntegerDivideByZero | NonnullAttribute | Null | ObjectSize | PointerOverflow | Return | ReturnsNonnullAttribute | Shift | SignedIntegerOverflow | Unreachable | VLABound | Function | -Vptr) +Vptr | SignedIntegerWrap) // -fsanitize=undefined-trap is an alias for -fsanitize=undefined. SANITIZER_GROUP("undefined-trap", UndefinedTrap, Undefined) @@ -179,7 +180,7 @@ SANITIZER_GROUP("implicit-conversion", ImplicitConversion, SANITIZER_GROUP("integer", Integer, ImplicitConversion | IntegerDivideByZero | Shift | SignedIntegerOverflow | UnsignedIntegerOverflow | -UnsignedShiftBase) +UnsignedShiftBase | SignedIntegerWrap) SANITIZER("local-bounds", LocalBounds) SANITIZER_GROUP("bounds", Bounds, ArrayBounds | LocalBounds) diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index aa805f291d1757..5c05a0d7524244 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -723,6 +723,11 @@ class ScalarExprEmitter if (Ops.Ty->isSignedIntegerOrEnumerationType()) { switch (CGF.getLangOpts().getSignedOverflowBehavior()) { case LangOptions::SOB_Defined: +if (CGF.SanOpts.has(SanitizerKind::SignedIntegerWrap)) { + if (CanElideOverflowCheck(CGF.getContext(), Ops)) +return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); + return EmitOverflowCheckedBinOp(Ops); +} return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); case LangOptions::SOB_Undefined: if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) @@ -2516,6 +2521,12 @@ llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( StringRef Name = IsInc ? "inc" : "dec"; switch (CGF.getLangOpts().getSignedOverflowBehavior()) { case LangOptions::SOB_Defined: +if (CGF.SanOpts.has(SanitizerKind::SignedIntegerWrap)) { + if (!E->canOverflow()) +return Builder.CreateNSWAdd(InVal, Amount, Name); + return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec( + E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts(; +} return Builder.CreateAdd(InVal, Amount, Name); case LangOptions::SOB_Undefined: if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) @@ -3409,7 +3420,7 @@ Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { - SmallVector, 2> Checks; + SmallVector, 3> Checks; if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), @@ -3417,7 +3428,8 @@ void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( } const auto *BO = cast(Ops.E); - if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && + if (CGF.SanOpts.hasOneOf(SanitizerKind::SignedIntegerOverflow | + SanitizerKind::SignedIntegerWrap) && Ops.Ty->hasSignedIntegerRepresentation() && !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) && Ops.mayHaveIntegerOverflow()) { @@ -3430,8 +3442,13 @@ void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); -Checks.push_back( -std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); +if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) + Checks.push_back( + std::make_pair(NotO
[clang] [-Wunsafe-buffer-usage] Fixits for unsafe arguments of function pointer calls (PR #80358)
https://github.com/jkorous-apple updated https://github.com/llvm/llvm-project/pull/80358 >From dfc9d95c185f5228f5c9680a19aa396d20e33d19 Mon Sep 17 00:00:00 2001 From: Jan Korous Date: Thu, 25 Jan 2024 13:52:12 -0800 Subject: [PATCH 1/3] [-Wunsafe-buffer-usage] Emit fixits for arguments of function pointers calls Currently we ignore calls on function pointers (unlike direct calls of functions and class methods). This patch adds support for function pointers as well. The change is to simply replace use of forEachArgumentWithParam matcher in UPC gadget with forEachArgumentWithParamType. from the documentation of forEachArgumentWithParamType: /// Matches all arguments and their respective types for a \c CallExpr or /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but /// it works on calls through function pointers as well. Currently the matcher also uses hasPointerType() which checks that the canonical type of an argument is pointer and won't match on arrays decayed to pointer. Replacing hasPointerType() with isAnyPointerType() which allows implicit casts allows for the arrays to be matched as well and this way we get fixits for array arguments to function pointer calls too. --- clang/lib/Analysis/UnsafeBufferUsage.cpp | 4 ++-- ...fer-usage-fixits-pointer-arg-to-func-ptr-call.cpp | 12 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp index d00c598c4b9de3..c5a87f14bc8880 100644 --- a/clang/lib/Analysis/UnsafeBufferUsage.cpp +++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp @@ -282,8 +282,8 @@ isInUnspecifiedPointerContext(internal::Matcher InnerMatcher) { //(i.e., computing the distance between two pointers); or ... auto CallArgMatcher = - callExpr(forEachArgumentWithParam(InnerMatcher, - hasPointerType() /* array also decays to pointer type*/), + callExpr(forEachArgumentWithParamType(InnerMatcher, + isAnyPointer() /* array also decays to pointer type*/), unless(callee(functionDecl(hasAttr(attr::UnsafeBufferUsage); auto CastOperandMatcher = diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp new file mode 100644 index 00..ae761e46a98191 --- /dev/null +++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp @@ -0,0 +1,12 @@ +// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage \ +// RUN:-fsafe-buffer-usage-suggestions \ +// RUN:-fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s + +void unsafe_array_func_ptr_call(void (*fn_ptr)(int *param)) { + int p[32]; + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array p" + + int tmp = p[5]; + fn_ptr(p); + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:11}:".data()" +} >From 44dab965c459f2cd6084ea332f4a6756f57254e0 Mon Sep 17 00:00:00 2001 From: Jan Korous Date: Thu, 1 Feb 2024 14:44:01 -0800 Subject: [PATCH 2/3] [-Wunsafe-buffer-usage][NFC] Add tests for function pointer call fixits --- ...ge-fixits-pointer-arg-to-func-ptr-call.cpp | 38 ++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp index ae761e46a98191..0459d6549fd86f 100644 --- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp +++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-arg-to-func-ptr-call.cpp @@ -6,7 +6,43 @@ void unsafe_array_func_ptr_call(void (*fn_ptr)(int *param)) { int p[32]; // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array p" - int tmp = p[5]; + p[5] = 10; fn_ptr(p); // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:11}:".data()" } + +void unsafe_ptr_func_ptr_call(void (*fn_ptr)(int *param)) { + int *p; + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:9}:"std::span p" + + p[5] = 10; + fn_ptr(p); + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:11}:".data()" +} + +void addr_of_unsafe_ptr_func_ptr_call(void (*fn_ptr)(int *param)) { + int *p; + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:9}:"std::span p" + + p[5] = 10; + fn_ptr(&p[0]); + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:15}:"p.data()" +} + +void addr_of_unsafe_ptr_w_offset_func_ptr_call(void (*fn_ptr)(int *param)) { + int *p; + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:9}:"std::span p" + + p[5] = 10; + fn_ptr(&p[3]); + // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:15}:"&p.
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 : def int_amdgcn_fdot2_bf16_bf16 : ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">, DefaultAttrsIntrinsic< -[llvm_i16_ty], // %r +[llvm_bfloat_ty], // %r rampitec wrote: clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl fails. You need to insert casts to bf16 while lowering it to make it working. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -4185,9 +4185,17 @@ bool SIInstrInfo::isInlineConstant(const MachineOperand &MO, case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: return AMDGPU::isInlinableLiteralV2F16(Imm); + case AMDGPU::OPERAND_REG_IMM_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_C_V2BF16: + case AMDGPU::OPERAND_REG_INLINE_AC_V2BF16: +return AMDGPU::isInlinableLiteralV2BF16(Imm); + case AMDGPU::OPERAND_REG_IMM_BF16: case AMDGPU::OPERAND_REG_IMM_FP16: + case AMDGPU::OPERAND_REG_IMM_BF16_DEFERRED: case AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED: + case AMDGPU::OPERAND_REG_INLINE_C_BF16: case AMDGPU::OPERAND_REG_INLINE_C_FP16: + case AMDGPU::OPERAND_REG_INLINE_AC_BF16: rampitec wrote: It seems isInlinableLiteral16() cannot handle bf16? https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -488,6 +488,49 @@ static bool printImmediateFloat16(uint32_t Imm, const MCSubtargetInfo &STI, return true; } +static bool printImmediateBFloat16(uint32_t Imm, const MCSubtargetInfo &STI, + raw_ostream &O) { + if (Imm == 0x3F80) +O << "1.0"; + else if (Imm == 0xBF80) +O << "-1.0"; + else if (Imm == 0x3F00) +O << "0.5"; + else if (Imm == 0xBF00) +O << "-0.5"; + else if (Imm == 0x4000) +O << "2.0"; + else if (Imm == 0xC000) +O << "-2.0"; + else if (Imm == 0x4080) +O << "4.0"; + else if (Imm == 0xC080) +O << "-4.0"; + else if (Imm == 0x3E22 && STI.hasFeature(AMDGPU::FeatureInv2PiInlineImm)) +O << "0.15915494"; + else +return false; + + return true; +} + +void AMDGPUInstPrinter::printImmediateBF16(uint32_t Imm, + const MCSubtargetInfo &STI, + raw_ostream &O) { + int16_t SImm = static_cast(Imm); + if (isInlinableIntLiteral(SImm)) { +O << SImm; +return; + } + + uint16_t HImm = static_cast(Imm); + if (printImmediateBFloat16(HImm, STI, O)) +return; + + uint64_t Imm16 = static_cast(Imm); rampitec wrote: It's the same as HImm above. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -1,8 +1,7 @@ ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py ; RUN: llc -mtriple=amdgcn -mcpu=gfx1100 -verify-machineinstrs < %s | FileCheck %s --check-prefixes=GFX11,SDAG-GFX11 -; RUN: llc -global-isel -mtriple=amdgcn -mcpu=gfx1100 -verify-machineinstrs < %s | FileCheck %s --check-prefixes=GFX11,GISEL-GFX11 rampitec wrote: Change 'RUN' with 'XUN' and add a comment instead. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)
@@ -0,0 +1,8 @@ +// RUN: llvm-mc -arch=amdgcn -mcpu=gfx1100 -show-encoding %s | FileCheck %s rampitec wrote: You also need a disasm test for this. https://github.com/llvm/llvm-project/pull/80908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ObjC] Check entire chain of superclasses to see if class layout can be statically known (PR #81335)
https://github.com/AtariDreams updated https://github.com/llvm/llvm-project/pull/81335 >From 6917791b07ad4fe696e7d5d1e9f378eb0e5ed78d Mon Sep 17 00:00:00 2001 From: Rose <83477269+ataridre...@users.noreply.github.com> Date: Fri, 9 Feb 2024 17:51:15 -0500 Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC] --- .../constant-non-fragile-ivar-offset.m| 56 +++ 1 file changed, 56 insertions(+) diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m index 788b3220af3067..44e5af28cdbe02 100644 --- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m +++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m @@ -1,6 +1,12 @@ // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | FileCheck %s // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 20 +// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20 +// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 24 +// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 32 +// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 40 +// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden global i64 48 +// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden global i64 12 @interface NSObject { @@ -20,6 +26,56 @@ -(void)meth { } @end +// Ivars declared in the @interface +@interface SuperClass : NSObject +@property (nonatomic, assign) int superClassProperty; +@end + +@implementation SuperClass { + int superClassIvar; // Declare an ivar +} +- (void)superClassMethod { +_superClassProperty = 42; +superClassIvar = 10; +// CHECK-NOT: load i64, ptr @"OBJC_IVAR_$_SuperClass +} +@end + +// Inheritance and Ivars +@interface IntermediateClass : SuperClass +{ +double intermediateClassIvar; + +@protected +int intermediateClassIvar2; +} +@property (nonatomic, strong) SuperClass *intermediateProperty; +@end + +@implementation IntermediateClass +@synthesize intermediateProperty = _intermediateProperty; +- (void)intermediateClassMethod { +intermediateClassIvar = 3.14; +_intermediateProperty = 0; +// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass +} +@end + +@interface SubClass : IntermediateClass +{ +double subClassIvar; +} +@end + +@implementation SubClass +- (void)subclassVar { +intermediateClassIvar = 3.14; +subClassIvar = 6.28; +// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass +// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass +} +@end + @interface NotNSObject { int these, might, change; } >From f5b3fd7ab12b3fba488c1f352f7f567cbc8a1fad Mon Sep 17 00:00:00 2001 From: Rose <83477269+ataridre...@users.noreply.github.com> Date: Tue, 13 Feb 2024 14:52:49 -0500 Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class layout can be statically known As of now, we only check if a class directly inherits from NSObject to determine if said class has fixed offsets and can therefore have its memory layout statically known. However, if an NSObject subclass has fixed offsets, then so must the subclasses of that subclass, so this allows us to optimize instances of subclasses of subclasses that inherit from NSObject and so on. To determine this, we need to find that the compiler can see the implementation of each intermediate class, as that means it is statically linked. --- clang/lib/CodeGen/CGObjCMac.cpp | 22 ++- .../constant-non-fragile-ivar-offset.m| 14 ++-- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp index 27d77e9a8a5511..b3d6c3ba314cc2 100644 --- a/clang/lib/CodeGen/CGObjCMac.cpp +++ b/clang/lib/CodeGen/CGObjCMac.cpp @@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac { } bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) { -// NSObject is a fixed size. If we can see the @implementation of a class -// which inherits from NSObject then we know that all it's offsets also must -// be fixed. FIXME: Can we do this if see a chain of super classes with -// implementations leading to NSObject? -return ID->getImplementation() && ID->getSuperClass() && - ID->getSuperClass()->getName() == "NSObject"; +// Test a class by checking its superclasses up to its base class if it has +// one +while (ID) { + // The base class NSObject is a fixed size + if (ID->getName() == "NSObject") +return true; + + // If we cannot see the @implementation of a class, we cannot statically + // know the class layout + if (!ID->getImplementation()) +return false; + + // Test superclass + ID =
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
@@ -183,6 +196,22 @@ class UncountedCallArgsChecker Report->addRange(CallArg->getSourceRange()); BR->emitReport(std::move(Report)); } + + void reportBugOnThis(const Expr *CallArg) const { +assert(CallArg); + +SmallString<100> Buf; +llvm::raw_svector_ostream Os(Buf); + +Os << "Call argument for 'this' parameter is uncounted and unsafe."; haoNoQ wrote: This is a constant string, no need to stream it, just put it straight into the `BugReport` constructor. https://github.com/llvm/llvm-project/pull/81400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [-Wunsafe-buffer-usage] Fixits for unsafe arguments of function pointer calls (PR #80358)
@@ -282,8 +282,8 @@ isInUnspecifiedPointerContext(internal::Matcher InnerMatcher) { //(i.e., computing the distance between two pointers); or ... auto CallArgMatcher = - callExpr(forEachArgumentWithParam(InnerMatcher, - hasPointerType() /* array also decays to pointer type*/), + callExpr(forEachArgumentWithParamType(InnerMatcher, + isAnyPointer() /* array also decays to pointer type*/), jkorous-apple wrote: Removing `hasCanonicalType()` is intentional but not well communicated by the commit message - I'll fix that. There's 2 different things going on and I probably could've separated this tiny change into two even-more-tiny changes. 1. Support for calls on function pointers - that's mostly the `forEachArgumentWithParam` -> `forEachArgumentWithParamType`. 2. Suport for const size arrays - that's removing the `hasCanonicalType()` to allow for array to pointer decay (which the comment in the snippet suggests we already expected). https://github.com/llvm/llvm-project/pull/80358 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Check the safety of the object argument in a member function call. (PR #81400)
@@ -70,6 +70,15 @@ class UncountedCallArgsChecker // or std::function call operator). unsigned ArgIdx = isa(CE) && isa_and_nonnull(F); + if (auto *MemberCallExpr = dyn_cast(CE)) { +auto *E = MemberCallExpr->getImplicitObjectArgument(); +auto *ArgType = MemberCallExpr->getObjectType().getTypePtrOrNull(); haoNoQ wrote: ```suggestion QualType ArgType = MemberCallExpr->getObjectType(); ``` `getTypePtrOrNull()` is typically redundant; `QualType` provides an overloaded `operator ->()` that allows you to call methods on the underlying unqualified `Type` directly. https://github.com/llvm/llvm-project/pull/81400 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [-Wunsafe-buffer-usage] Fixits for unsafe arguments of function pointer calls (PR #80358)
@@ -282,8 +282,8 @@ isInUnspecifiedPointerContext(internal::Matcher InnerMatcher) { //(i.e., computing the distance between two pointers); or ... auto CallArgMatcher = - callExpr(forEachArgumentWithParam(InnerMatcher, - hasPointerType() /* array also decays to pointer type*/), + callExpr(forEachArgumentWithParamType(InnerMatcher, + isAnyPointer() /* array also decays to pointer type*/), haoNoQ wrote: Original code uses `hasPointerType()` which is inconvenient here because it includes the `hasType()` part, but another thing it was doing was `hasCanonicalType()` which is now missing. Are you sure it's not necessary in this case? https://github.com/llvm/llvm-project/pull/80358 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
https://github.com/JustinStitt updated https://github.com/llvm/llvm-project/pull/80089 >From 7774e4036ac1de7fdf5fe4c6b3208b492853ffc5 Mon Sep 17 00:00:00 2001 From: Justin Stitt Date: Tue, 23 Jan 2024 23:28:42 + Subject: [PATCH 1/9] add signed-integer-wrap sanitizer --- clang/include/clang/Basic/Sanitizers.def | 5 +- clang/lib/CodeGen/CGExprScalar.cpp | 62 +++- compiler-rt/lib/ubsan/ubsan_checks.inc | 2 + 3 files changed, 54 insertions(+), 15 deletions(-) diff --git a/clang/include/clang/Basic/Sanitizers.def b/clang/include/clang/Basic/Sanitizers.def index c2137e3f61f645..b987b26f93c39a 100644 --- a/clang/include/clang/Basic/Sanitizers.def +++ b/clang/include/clang/Basic/Sanitizers.def @@ -104,6 +104,7 @@ SANITIZER("shift-base", ShiftBase) SANITIZER("shift-exponent", ShiftExponent) SANITIZER_GROUP("shift", Shift, ShiftBase | ShiftExponent) SANITIZER("signed-integer-overflow", SignedIntegerOverflow) +SANITIZER("signed-integer-wrap", SignedIntegerWrap) SANITIZER("unreachable", Unreachable) SANITIZER("vla-bound", VLABound) SANITIZER("vptr", Vptr) @@ -144,7 +145,7 @@ SANITIZER_GROUP("undefined", Undefined, IntegerDivideByZero | NonnullAttribute | Null | ObjectSize | PointerOverflow | Return | ReturnsNonnullAttribute | Shift | SignedIntegerOverflow | Unreachable | VLABound | Function | -Vptr) +Vptr | SignedIntegerWrap) // -fsanitize=undefined-trap is an alias for -fsanitize=undefined. SANITIZER_GROUP("undefined-trap", UndefinedTrap, Undefined) @@ -179,7 +180,7 @@ SANITIZER_GROUP("implicit-conversion", ImplicitConversion, SANITIZER_GROUP("integer", Integer, ImplicitConversion | IntegerDivideByZero | Shift | SignedIntegerOverflow | UnsignedIntegerOverflow | -UnsignedShiftBase) +UnsignedShiftBase | SignedIntegerWrap) SANITIZER("local-bounds", LocalBounds) SANITIZER_GROUP("bounds", Bounds, ArrayBounds | LocalBounds) diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp index aa805f291d1757..5c05a0d7524244 100644 --- a/clang/lib/CodeGen/CGExprScalar.cpp +++ b/clang/lib/CodeGen/CGExprScalar.cpp @@ -723,6 +723,11 @@ class ScalarExprEmitter if (Ops.Ty->isSignedIntegerOrEnumerationType()) { switch (CGF.getLangOpts().getSignedOverflowBehavior()) { case LangOptions::SOB_Defined: +if (CGF.SanOpts.has(SanitizerKind::SignedIntegerWrap)) { + if (CanElideOverflowCheck(CGF.getContext(), Ops)) +return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); + return EmitOverflowCheckedBinOp(Ops); +} return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); case LangOptions::SOB_Undefined: if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) @@ -2516,6 +2521,12 @@ llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( StringRef Name = IsInc ? "inc" : "dec"; switch (CGF.getLangOpts().getSignedOverflowBehavior()) { case LangOptions::SOB_Defined: +if (CGF.SanOpts.has(SanitizerKind::SignedIntegerWrap)) { + if (!E->canOverflow()) +return Builder.CreateNSWAdd(InVal, Amount, Name); + return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec( + E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts(; +} return Builder.CreateAdd(InVal, Amount, Name); case LangOptions::SOB_Undefined: if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) @@ -3409,7 +3420,7 @@ Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { - SmallVector, 2> Checks; + SmallVector, 3> Checks; if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), @@ -3417,7 +3428,8 @@ void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( } const auto *BO = cast(Ops.E); - if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && + if (CGF.SanOpts.hasOneOf(SanitizerKind::SignedIntegerOverflow | + SanitizerKind::SignedIntegerWrap) && Ops.Ty->hasSignedIntegerRepresentation() && !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) && Ops.mayHaveIntegerOverflow()) { @@ -3430,8 +3442,13 @@ void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); -Checks.push_back( -std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); +if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) + Checks.push_back( + std::make_pair(NotOve
[clang] Add comments and macros support to Python bindings (PR #81684)
github-actions[bot] wrote: :warning: Python code formatter, darker found issues in your code. :warning: You can test this locally with the following command: ``bash darker --check --diff -r fd3a0c185f177351207783fc2a604dac086cdaf7...497478f08570f1333966c0843d713268bc9ba5c7 clang/bindings/python/clang/cindex.py `` View the diff from darker here. ``diff --- cindex.py 2024-02-13 23:12:05.00 + +++ cindex.py 2024-02-13 23:17:41.291558 + @@ -2260,21 +2260,22 @@ TypeKind.EXTVECTOR = TypeKind(176) TypeKind.ATOMIC = TypeKind(177) ### Comment Kinds ### + class CommentKind(BaseEnumeration): """ Describes the kind of comment. """ # The unique kind objects, indexed by id. _kinds = [] _name_map = None def __repr__(self): -return 'CommentKind.%s' % (self.name,) +return "CommentKind.%s" % (self.name,) CommentKind.NULL = CommentKind(0) CommentKind.TEXT = CommentKind(1) CommentKind.INLINECOMMAND = CommentKind(2) @@ -2292,16 +2293,17 @@ class CommentInlineCommandRenderKind(BaseEnumeration): """ Describes the kind of rendering mode of an inline command. """ + # The unique kind objects, indexed by id. _kinds = [] _name_map = None def __repr__(self): -return 'CommentInlineCommandRenderKind.%s' % (self.name,) +return "CommentInlineCommandRenderKind.%s" % (self.name,) CommentInlineCommandRenderKind.NORMAL = CommentInlineCommandRenderKind(0) CommentInlineCommandRenderKind.BOLD = CommentInlineCommandRenderKind(1) CommentInlineCommandRenderKind.MONOSPACED = CommentInlineCommandRenderKind(2) @@ -2311,22 +2313,22 @@ class CommentParamPassDirection(BaseEnumeration): """ Describes the kind of parameter passing direction for \\param or \\arg command """ + # The unique kind objects, indexed by id. _kinds = [] _name_map = None def __repr__(self): -return 'CommentParamPassDirection.%s' % (self.name,) +return "CommentParamPassDirection.%s" % (self.name,) CommentParamPassDirection.IN = CommentParamPassDirection(0) CommentParamPassDirection.OUT = CommentParamPassDirection(1) CommentParamPassDirection.INOU = CommentParamPassDirection(2) - class RefQualifierKind(BaseEnumeration): """Describes a specific ref-qualifier of a type.""" @@ -3655,14 +3657,17 @@ None, c_object_p, POINTER(SourceLocation), c_uint, py_object ) callbacks["cursor_visit"] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) callbacks["fields_visit"] = CFUNCTYPE(c_int, Cursor, py_object) + class CXTranslationUnitImpl(Structure): -pass # opaque structure +pass # opaque structure + CXTranslationUnit = POINTER(CXTranslationUnitImpl) + class Comment(Structure): _fields_ = [("ASTNode", c_void_p), ("TranslationUnit", CXTranslationUnit)] def get_text(self): @@ -3678,10 +3683,11 @@ """Get number of child nodes.""" return conf.lib.clang_Comment_getNumChildren(self) def get_children(self): """Return an iterator for accessing the children of this comment.""" + def cast_child(child): if child.kind == CommentKind.INLINECOMMAND: child.__class__ = InlineCommand if child.kind == CommentKind.HTMLSTARTTAG: child.__class__ = HTMLComment @@ -3690,23 +3696,25 @@ if child.kind == CommentKind.BLOCKCOMMAND: child.__class__ = BlockCommandComment if child.kind == CommentKind.PARAMCOMMAND: child.__class__ = ParamCommandComment if child.kind == CommentKind.TPARAMCOMMAND: -child.__class__ = TParamCommandComment +child.__class__ = TParamCommandComment if child.kind == CommentKind.VERBATIMBLOCKLINE: child.__class__ = VerbatimBlockLineComment if child.kind == CommentKind.VERBATIMLINE: child.__class__ = VerbatimLineComment if child.kind == CommentKind.FULLCOMMENT: child.__class__ = FullComment # if child.kind == CommentKind.PARAGRAPH: # if child.kind == CommentKind.VERBATIMBLOCKCOMMAND: return child -return (cast_child(conf.lib.clang_Comment_getChild(self, i)) -for i in range(self.num_children())) +return ( +cast_child(conf.lib.clang_Comment_getChild(self, i)) +for i in range(self.num_children()) +) def is_whitespace(self): """Check if all paragraph nodes are space or empty.""" return conf.lib.clang_Comment_isWhitespace(self) @@ -3727,12 +3735,14 @@ def get_num_args(self): conf.lib.clang_InlineCommandComment_getNumArgs(self) def get_args(self): -return (conf.lib.clang_InlineCommandComment_getArgText(self, i) -for i in range(self.get_num_args()))
[clang] Add comments and macros support to Python bindings (PR #81684)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Dan Miller (dnmiller) Changes The Python bindings currently do not expose the comment parsing engine and are missing a few macro utility functions. This adds bindings for the comments. --- Full diff: https://github.com/llvm/llvm-project/pull/81684.diff 1 Files Affected: - (modified) clang/bindings/python/clang/cindex.py (+284) ``diff diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 44a34ca196274c..542bc0172a56fa 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -1907,6 +1907,11 @@ def raw_comment(self): """Returns the raw comment text associated with that Cursor""" return conf.lib.clang_Cursor_getRawCommentText(self) +@property +def parsed_comment(self): +"""Returns the parsed comment text associaetd with that Cursor""" +return conf.lib.clang_Cursor_getParsedComment(self) + def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) @@ -1994,6 +1999,18 @@ def get_bitfield_width(self): """ return conf.lib.clang_getFieldDeclBitWidth(self) +def is_macro_function(self): +""" +Check if the field is a macro function. +""" +return conf.lib.clang_Cursor_isMacroFunctionLike(self) + +def is_macro_builtin(self): +""" +Check if the field is a macro function. +""" +return conf.lib.clang_Cursor_isMacroBuiltin(self) + @staticmethod def from_result(res, fn, args): assert isinstance(res, Cursor) @@ -2243,6 +2260,72 @@ def __repr__(self): TypeKind.EXTVECTOR = TypeKind(176) TypeKind.ATOMIC = TypeKind(177) +### Comment Kinds ### + +class CommentKind(BaseEnumeration): +""" +Describes the kind of comment. +""" + +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return 'CommentKind.%s' % (self.name,) + + +CommentKind.NULL = CommentKind(0) +CommentKind.TEXT = CommentKind(1) +CommentKind.INLINECOMMAND = CommentKind(2) +CommentKind.HTMLSTARTTAG = CommentKind(3) +CommentKind.HTMLENDTAG = CommentKind(4) +CommentKind.PARAGRAPH = CommentKind(5) +CommentKind.BLOCKCOMMAND = CommentKind(6) +CommentKind.PARAMCOMMAND = CommentKind(7) +CommentKind.TPARAMCOMMAND = CommentKind(8) +CommentKind.VERBATIMBLOCKCOMMAND = CommentKind(9) +CommentKind.VERBATIMBLOCKLINE = CommentKind(10) +CommentKind.VERBATIMLINE = CommentKind(11) +CommentKind.FULLCOMMENT = CommentKind(12) + + +class CommentInlineCommandRenderKind(BaseEnumeration): +""" +Describes the kind of rendering mode of an inline command. +""" +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return 'CommentInlineCommandRenderKind.%s' % (self.name,) + + +CommentInlineCommandRenderKind.NORMAL = CommentInlineCommandRenderKind(0) +CommentInlineCommandRenderKind.BOLD = CommentInlineCommandRenderKind(1) +CommentInlineCommandRenderKind.MONOSPACED = CommentInlineCommandRenderKind(2) +CommentInlineCommandRenderKind.EMPHASIZE = CommentInlineCommandRenderKind(3) + + +class CommentParamPassDirection(BaseEnumeration): +""" +Describes the kind of parameter passing direction for \\param +or \\arg command +""" +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return 'CommentParamPassDirection.%s' % (self.name,) + + +CommentParamPassDirection.IN = CommentParamPassDirection(0) +CommentParamPassDirection.OUT = CommentParamPassDirection(1) +CommentParamPassDirection.INOU = CommentParamPassDirection(2) + + class RefQualifierKind(BaseEnumeration): """Describes a specific ref-qualifier of a type.""" @@ -3574,6 +3657,171 @@ def write_main_file_to_stdout(self): callbacks["cursor_visit"] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) callbacks["fields_visit"] = CFUNCTYPE(c_int, Cursor, py_object) +class CXTranslationUnitImpl(Structure): +pass # opaque structure + +CXTranslationUnit = POINTER(CXTranslationUnitImpl) + +class Comment(Structure): +_fields_ = [("ASTNode", c_void_p), ("TranslationUnit", CXTranslationUnit)] + +def get_text(self): +return conf.lib.clang_TextComment_getText(self) + +@property +def kind(self): +"""Return the kind of this comment.""" +kind_id = conf.lib.clang_Comment_getKind(self) +return CommentKind.from_id(kind_id) + +def num_children(self): +"""Get number of child nodes.""" +return conf.lib.clang_Comment_getNumChildren(self) + +def get_children(self): +"""Return an iterator for accessing the children of this comment.""" +def cast_child(child): +if child.kind == CommentKind.INLINECOMMAND: +
[clang] Add comments and macros support to Python bindings (PR #81684)
https://github.com/dnmiller created https://github.com/llvm/llvm-project/pull/81684 The Python bindings currently do not expose the comment parsing engine and are missing a few macro utility functions. This adds bindings for the comments. >From 497478f08570f1333966c0843d713268bc9ba5c7 Mon Sep 17 00:00:00 2001 From: "Daniel N. Miller (APD)" Date: Tue, 13 Feb 2024 15:12:05 -0800 Subject: [PATCH] Add comments and macros support to Python bindings --- clang/bindings/python/clang/cindex.py | 284 ++ 1 file changed, 284 insertions(+) diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 44a34ca196274c..542bc0172a56fa 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -1907,6 +1907,11 @@ def raw_comment(self): """Returns the raw comment text associated with that Cursor""" return conf.lib.clang_Cursor_getRawCommentText(self) +@property +def parsed_comment(self): +"""Returns the parsed comment text associaetd with that Cursor""" +return conf.lib.clang_Cursor_getParsedComment(self) + def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) @@ -1994,6 +1999,18 @@ def get_bitfield_width(self): """ return conf.lib.clang_getFieldDeclBitWidth(self) +def is_macro_function(self): +""" +Check if the field is a macro function. +""" +return conf.lib.clang_Cursor_isMacroFunctionLike(self) + +def is_macro_builtin(self): +""" +Check if the field is a macro function. +""" +return conf.lib.clang_Cursor_isMacroBuiltin(self) + @staticmethod def from_result(res, fn, args): assert isinstance(res, Cursor) @@ -2243,6 +2260,72 @@ def __repr__(self): TypeKind.EXTVECTOR = TypeKind(176) TypeKind.ATOMIC = TypeKind(177) +### Comment Kinds ### + +class CommentKind(BaseEnumeration): +""" +Describes the kind of comment. +""" + +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return 'CommentKind.%s' % (self.name,) + + +CommentKind.NULL = CommentKind(0) +CommentKind.TEXT = CommentKind(1) +CommentKind.INLINECOMMAND = CommentKind(2) +CommentKind.HTMLSTARTTAG = CommentKind(3) +CommentKind.HTMLENDTAG = CommentKind(4) +CommentKind.PARAGRAPH = CommentKind(5) +CommentKind.BLOCKCOMMAND = CommentKind(6) +CommentKind.PARAMCOMMAND = CommentKind(7) +CommentKind.TPARAMCOMMAND = CommentKind(8) +CommentKind.VERBATIMBLOCKCOMMAND = CommentKind(9) +CommentKind.VERBATIMBLOCKLINE = CommentKind(10) +CommentKind.VERBATIMLINE = CommentKind(11) +CommentKind.FULLCOMMENT = CommentKind(12) + + +class CommentInlineCommandRenderKind(BaseEnumeration): +""" +Describes the kind of rendering mode of an inline command. +""" +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return 'CommentInlineCommandRenderKind.%s' % (self.name,) + + +CommentInlineCommandRenderKind.NORMAL = CommentInlineCommandRenderKind(0) +CommentInlineCommandRenderKind.BOLD = CommentInlineCommandRenderKind(1) +CommentInlineCommandRenderKind.MONOSPACED = CommentInlineCommandRenderKind(2) +CommentInlineCommandRenderKind.EMPHASIZE = CommentInlineCommandRenderKind(3) + + +class CommentParamPassDirection(BaseEnumeration): +""" +Describes the kind of parameter passing direction for \\param +or \\arg command +""" +# The unique kind objects, indexed by id. +_kinds = [] +_name_map = None + +def __repr__(self): +return 'CommentParamPassDirection.%s' % (self.name,) + + +CommentParamPassDirection.IN = CommentParamPassDirection(0) +CommentParamPassDirection.OUT = CommentParamPassDirection(1) +CommentParamPassDirection.INOU = CommentParamPassDirection(2) + + class RefQualifierKind(BaseEnumeration): """Describes a specific ref-qualifier of a type.""" @@ -3574,6 +3657,171 @@ def write_main_file_to_stdout(self): callbacks["cursor_visit"] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) callbacks["fields_visit"] = CFUNCTYPE(c_int, Cursor, py_object) +class CXTranslationUnitImpl(Structure): +pass # opaque structure + +CXTranslationUnit = POINTER(CXTranslationUnitImpl) + +class Comment(Structure): +_fields_ = [("ASTNode", c_void_p), ("TranslationUnit", CXTranslationUnit)] + +def get_text(self): +return conf.lib.clang_TextComment_getText(self) + +@property +def kind(self): +"""Return the kind of this comment.""" +kind_id = conf.lib.clang_Comment_getKind(self) +return CommentKind.from_id(kind_id) + +def num_children(self): +"""Get number of child nodes.""" +return conf.lib.clang_Comment_getNumChildren(self) + +def get_children(self): +"""Return a
[clang] Add comments and macros support to Python bindings (PR #81684)
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/81684 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] bad error message on incorrect string literal #18079 (PR #81670)
jroelofs wrote: > I am new to this project. Please let me know if any files need to be added. > > I don't believe any testing or test suite changes are required for this > change. This particular change will break this usage of that diagnostic, which expects that format argument: https://github.com/llvm/llvm-project/blob/e06f3522cc55cec60084a1278109ab236ef7a3ee/clang/lib/Lex/Lexer.cpp#L2274-L2275 The change needs to account for cases where the character should still be printed, and when it isn't printable or would have strange formatting. And then it should be accompanied by a test that verifies the new behavior. https://github.com/llvm/llvm-project/pull/81670 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [attributes][analyzer] Generalize [[clang::suppress]] to declarations. (PR #80371)
https://github.com/haoNoQ closed https://github.com/llvm/llvm-project/pull/80371 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 017675f - [attributes][analyzer] Generalize [[clang::suppress]] to declarations. (#80371)
Author: Artem Dergachev Date: 2024-02-13T14:57:55-08:00 New Revision: 017675fff116c26bef7f0a389c983c909a3141fd URL: https://github.com/llvm/llvm-project/commit/017675fff116c26bef7f0a389c983c909a3141fd DIFF: https://github.com/llvm/llvm-project/commit/017675fff116c26bef7f0a389c983c909a3141fd.diff LOG: [attributes][analyzer] Generalize [[clang::suppress]] to declarations. (#80371) The attribute is now allowed on an assortment of declarations, to suppress warnings related to declarations themselves, or all warnings in the lexical scope of the declaration. I don't necessarily see a reason to have a list at all, but it does look as if some of those more niche items aren't properly supported by the compiler itself so let's maintain a short safe list for now. The initial implementation raised a question whether the attribute should apply to lexical declaration context vs. "actual" declaration context. I'm using "lexical" here because it results in less warnings suppressed, which is the conservative behavior: we can always expand it later if we think this is wrong, without breaking any existing code. I also think that this is the correct behavior that we will probably never want to change, given that the user typically desires to keep the suppressions as localized as possible. Added: clang/test/Analysis/suppression-attr.cpp Modified: clang/include/clang/Basic/Attr.td clang/include/clang/Basic/AttrDocs.td clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaDeclAttr.cpp clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp clang/lib/StaticAnalyzer/Core/BugSuppression.cpp clang/test/Analysis/Checkers/WebKit/ref-cntbl-base-virtual-dtor.cpp clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp clang/test/Analysis/ObjCRetSigs.m clang/test/Analysis/objc_invalidation.m clang/test/Analysis/suppression-attr-doc.cpp clang/test/Analysis/suppression-attr.m clang/test/Analysis/unused-ivars.m clang/test/SemaCXX/attr-suppress.cpp clang/test/SemaObjC/attr-suppress.m Removed: diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index 45a29e771f2a21..7e643b89971c17 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -2891,6 +2891,13 @@ def Suppress : DeclOrStmtAttr { let Spellings = [CXX11<"gsl", "suppress">, Clang<"suppress">]; let Args = [VariadicStringArgument<"DiagnosticIdentifiers">]; let Accessors = [Accessor<"isGSL", [CXX11<"gsl", "suppress">]>]; + // There's no fundamental reason why we can't simply accept all Decls + // but let's make a short list so that to avoid supporting something weird + // by accident. We can always expand the list later. + let Subjects = SubjectList<[ +Stmt, Var, Field, ObjCProperty, Function, ObjCMethod, Record, ObjCInterface, +ObjCImplementation, Namespace, Empty + ], ErrorDiag, "variables, functions, structs, interfaces, and namespaces">; let Documentation = [SuppressDocs]; } diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td index 8d369091d21590..b96fbddd51154c 100644 --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -5321,6 +5321,29 @@ Putting the attribute on a compound statement suppresses all warnings in scope: } } +The attribute can also be placed on entire declarations of functions, classes, +variables, member variables, and so on, to suppress warnings related +to the declarations themselves. When used this way, the attribute additionally +suppresses all warnings in the lexical scope of the declaration: + +.. code-block:: c++ + + class [[clang::suppress]] C { +int foo() { + int *x = nullptr; + ... + return *x; // warnings suppressed in the entire class scope +} + +int bar(); + }; + + int C::bar() { +int *x = nullptr; +... +return *x; // warning NOT suppressed! - not lexically nested in 'class C{}' + } + Some static analysis warnings are accompanied by one or more notes, and the line of code against which the warning is emitted isn't necessarily the best for suppression purposes. In such cases the tools are allowed to implement diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 375f92e4ac573c..e95e675d0507ed 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -2960,6 +2960,9 @@ static bool mergeDeclAttribute(Sema &S, NamedDecl *D, S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); else if (const auto *SA = dyn_cast(Attr)) NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType()); + else if (const auto *SupA = dyn_cast(Attr)) +// Do nothing. Each redeclaration
[clang] [attributes][analyzer] Generalize [[clang::suppress]] to declarations. (PR #80371)
haoNoQ wrote: Ok I'll try to land! https://github.com/llvm/llvm-project/pull/80371 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)
haoNoQ wrote: Closing because of the other PR. https://github.com/llvm/llvm-project/pull/68170 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)
https://github.com/haoNoQ closed https://github.com/llvm/llvm-project/pull/68170 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
@@ -0,0 +1,77 @@ +// Check that -fsanitize=signed-integer-wrap instruments with -fwrapv JustinStitt wrote: Gotcha, I did just that in [5497e8b](https://github.com/llvm/llvm-project/pull/80089/commits/5497e8bc6849bf64c1158ff16b4aa04fd9141920). Thanks Nick! https://github.com/llvm/llvm-project/pull/80089 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
@@ -0,0 +1,77 @@ +// Check that -fsanitize=signed-integer-wrap instruments with -fwrapv +// RUN: %clang_cc1 -fwrapv -triple x86_64-apple-darwin -emit-llvm -o - %s -fsanitize=signed-integer-wrap | FileCheck %s --check-prefix=CHECKSIW + +// Check that -fsanitize=signed-integer-overflow doesn't instrument with -fwrapv +// RUN: %clang_cc1 -fwrapv -triple x86_64-apple-darwin -emit-llvm -o - %s -fsanitize=signed-integer-overflow | FileCheck %s --check-prefix=CHECKSIO + +extern volatile int a, b, c; + +// CHECKSIW-LABEL: define void @test_add_overflow JustinStitt wrote: Resolved in [5497e8b](https://github.com/llvm/llvm-project/pull/80089/commits/5497e8bc6849bf64c1158ff16b4aa04fd9141920) since the tests have been moved there is no issue with LABEL statements or prefixes. https://github.com/llvm/llvm-project/pull/80089 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
@@ -0,0 +1,77 @@ +// Check that -fsanitize=signed-integer-wrap instruments with -fwrapv +// RUN: %clang_cc1 -fwrapv -triple x86_64-apple-darwin -emit-llvm -o - %s -fsanitize=signed-integer-wrap | FileCheck %s --check-prefix=CHECKSIW + +// Check that -fsanitize=signed-integer-overflow doesn't instrument with -fwrapv +// RUN: %clang_cc1 -fwrapv -triple x86_64-apple-darwin -emit-llvm -o - %s -fsanitize=signed-integer-overflow | FileCheck %s --check-prefix=CHECKSIO JustinStitt wrote: I moved the tests in [5497e8b](https://github.com/llvm/llvm-project/pull/80089/commits/5497e8bc6849bf64c1158ff16b4aa04fd9141920); as such, I am no longer adding tests related to SIO. https://github.com/llvm/llvm-project/pull/80089 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)
@@ -3554,12 +3572,20 @@ Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { const std::string *handlerName = &CGF.getLangOpts().OverflowHandler; if (handlerName->empty()) { -// If the signed-integer-overflow sanitizer is enabled, emit a call to its -// runtime. Otherwise, this is a -ftrapv check, so just emit a trap. -if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { +// If the signed-integer-overflow or signed-integer-wrap sanitizer is +// enabled, emit a call to its runtime. Otherwise, this is a -ftrapv check, +// so just emit a trap. +if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) || +CGF.SanOpts.has(SanitizerKind::SignedIntegerWrap)) { JustinStitt wrote: Yes, fixed in [e964431](https://github.com/llvm/llvm-project/pull/80089/commits/e96443184c6059ab8c5b97badc9ecc7270d4d466) https://github.com/llvm/llvm-project/pull/80089 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits