aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/CodeGen/CGExprConstant.cpp
AgeCommit message (Collapse)AuthorFilesLines
2023-09-28[CodeGen] Avoid use of ConstantExpr::getZExt() (NFC)Nikita Popov1-1/+5
Use the constant folding API instead. In preparation for dropping zext constant expressions.
2023-08-23[clang][CGExprConstant] Resolve unused variable 'C' warningBjorn Pettersson1-1/+1
2023-08-17[CodeGen] Remove Constant arguments from linkage functions, NFCI.Jonas Hahnfeld1-1/+1
This was unused since commit dd2362a8ba last year. Differential Revision: https://reviews.llvm.org/D156891
2023-08-14Make globals with mutable members non-constant, even in custom sectionsDavid Blaikie1-1/+1
Turned out we were making overly simple assumptions about which sections (& section flags) would be used when emitting a global into a custom section. This lead to sections with read-only flags being used for globals of struct types with mutable members. Fixed by porting the codegen function with the more nuanced handling/checking for mutable members out of codegen for use in the sema code that does this initial checking/mapping to section flags. Differential Revision: https://reviews.llvm.org/D156726
2023-08-07[clang][CGExprConstant] handle implicit widening/narrowing Int-to-Int castsNick Desaulniers1-1/+18
Consider the following statements: long x = 1; short y = 1; With the following AST: |-VarDecl 0x55d289973730 <x.c:1:1, col:10> col:6 x 'long' cinit | `-ImplicitCastExpr 0x55d289973800 <col:10> 'long' <IntegralCast> | `-IntegerLiteral 0x55d2899737e0 <col:10> 'int' 1 `-VarDecl 0x55d289973830 <line:2:1, col:11> col:7 y 'short' cinit `-ImplicitCastExpr 0x55d2899738b8 <col:11> 'short' <IntegralCast> `-IntegerLiteral 0x55d289973898 <col:11> 'int' 1 Sign or Zero extend or truncate based on the source signedness and destination width. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D156466
2023-08-07[clang][CGExprConstant] handle unary negation on integralsNick Desaulniers1-0/+7
Consider the statement: int x = -1; And the following AST: `-VarDecl 0x55c4823a7670 <x.c:2:1, col:10> col:5 x 'int' cinit `-UnaryOperator 0x55c4823a7740 <col:9, col:10> 'int' prefix '-' `-IntegerLiteral 0x55c4823a7720 <col:10> 'int' 1 Return the evaluation of the subexpression negated. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D156378
2023-07-26[clang][ConstExprEmitter] handle NullToPointer ImplicitCastExprNick Desaulniers1-1/+4
Consider the following statement: void* foo = ((void *)0); For the sub-AST: | `-ImplicitCastExpr 'const void *' <NullToPointer> | `-CStyleCastExpr 'void *' <NullToPointer> | `-IntegerLiteral 'int' 0 If the subexpression of the cast is itself the NULL constant, then ImplicitCastExpr should emit the NULL pointer constant. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D156175
2023-07-25[clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of ↵Nick Desaulniers1-1/+5
StringLiterals Consider the following statement: const char* foo = "foo"; For the sub-AST: `-ImplicitCastExpr <col:19> 'const char *' <NoOp> `-ImplicitCastExpr <col:19> 'char *' <ArrayToPointerDecay> `-StringLiteral <col:19> 'char[4]' lvalue "foo" The address of the StringLiteral can be emitted as the Constant. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D156185
2023-07-25[clang][ConstExprEmitter] handle IntegerLiteralsNick Desaulniers1-0/+4
Improves the ability of ConstExprEmitter to evaluate constants. Found by adding asserts to ConstantEmitter::tryEmitPrivate to find cases where ConstExprEmitter::Visit() fails to resolve (obvious) constants. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D156154
2023-07-24[clang][ConstantEmitter] have tryEmitPrivate[ForVarInit] try ↵Nick Desaulniers1-29/+23
ConstExprEmitter fast-path first As suggested by @efriedma in: https://reviews.llvm.org/D76096#4370369 This should speed up evaluating whether an expression is constant or not, but due to the complexity of these two different implementations, we may start getting different answers for edge cases for which we do not yet have test cases in-tree (or perhaps even performance regressions for some cases). As such, contributors have carte blanche to revert if necessary. For additional historical context about ExprConstant vs CGExprConstant, here's snippets from a private conversation on discord: ndesaulniers: why do we have clang/lib/AST/ExprConstant.cpp and clang/lib/CodeGen/CGExprConstant.cpp? Does clang constant fold during ast walking/creation AND during LLVM codegen? efriedma: originally, clang needed to handle two things: integer constant expressions (the "5" in "int x[5];"), and constant global initializers (the "5" in "int x = 5;"). pre-C++11, the two could be handled mostly separately; so we had the code for integer constants in AST/, and the code for globals in CodeGen/. C++11 constexpr sort of destroyed that separation, though. so now we do both kinds of constant evaluation on the AST, then CGExprConstant translates the result of that evaluation to LLVM IR. but we kept around some bits of the old cgexprconstant to avoid performance/memory usage regressions on large arrays. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D151587
2023-06-16[clang] Replace use of Type::getPointerTo() (NFC)Youngsuk Kim1-12/+2
Partial progress towards replacing in-tree uses of `Type::getPointerTo()`. This needs to be done before deprecating the API. Reviewed By: nikic, barannikov88 Differential Revision: https://reviews.llvm.org/D152321
2023-06-14[Clang] Rename getElementBitCast() -> withElementType() (NFC)Nikita Popov1-1/+1
This no longer creates a bitcast, just changes the element type of the ConstantAddress.
2023-05-25[NFC][CLANG] Fix static code analyzer concernsManna, Soumi1-0/+1
Reported by Static Code Analyzer Tool: Inside "CGExprConstant.cpp" file, VisitObjCEncodeExpr() returns null value which is dereferenced without checking. This patch adds an assert. Reviewed By: erichkeane Differential Revision: https://reviews.llvm.org/D151280
2023-05-23[CodeGen] Fix the type of the constant that is used to zero-initialize aAkira Hatanaka1-0/+5
flexible array member A zero-element array type was incorrectly being used when an incomplete array was being initialized with a non-empty initializer. This fixes an assertion failure in AddInitializerToStaticVarDecl. See the discussion here: https://reviews.llvm.org/D123649#4362210 Differential Revision: https://reviews.llvm.org/D151172
2023-05-02[clang] Do not attempt to zero-extend _BitInt(1) when not requiredMariya Podchishchaeva1-1/+1
`ConvertTypeForMem` doesn't return wider type for _BitInt unless it is used in a bitfield, so no need to extend when trying to initialize a global variable. Fixes https://github.com/llvm/llvm-project/issues/62207 Reviewed By: erichkeane, shafik Differential Revision: https://reviews.llvm.org/D149436
2023-03-16Emit const globals with constexpr destructor as constant LLVM valuesHans Wennborg1-6/+6
This follows 2b4fa53 which made Clang not emit destructor calls for such objects. However, they would still not get emitted as constants since CodeGenModule::isTypeConstant() returns false if the destructor is constexpr. This change adds a param to make isTypeConstant() ignore the dtor, allowing the caller to check it instead. Fixes Issue #61212 Differential revision: https://reviews.llvm.org/D145369
2023-03-15[clang] Use *{Map,Set}::contains (NFC)Kazu Hirata1-1/+1
2023-01-14[clang] Use std::optional instead of llvm::Optional (NFC)Kazu Hirata1-8/+8
This patch replaces (llvm::|)Optional< with std::optional<. I'll post a separate patch to remove #include "llvm/ADT/Optional.h". This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14[clang] Add #include <optional> (NFC)Kazu Hirata1-0/+1
This patch adds #include <optional> to those files containing llvm::Optional<...> or Optional<...>. I'll post a separate patch to actually replace llvm::Optional with std::optional. This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-13[clang][NFC] Remove dependency on DataLayout::getPrefTypeAlignmentGuillaume Chatelet1-1/+1
2023-01-09Move from llvm::makeArrayRef to ArrayRef deduction guides - clang/ partserge-sans-paille1-3/+3
This is a follow-up to https://reviews.llvm.org/D140896, split into several parts as it touches a lot of files. Differential Revision: https://reviews.llvm.org/D141139
2022-12-04[clang] Use std::nullopt instead of None in comments (NFC)Kazu Hirata1-1/+1
This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-12-03[CodeGen] Use std::nullopt instead of None (NFC)Kazu Hirata1-1/+1
This patch mechanically replaces None with std::nullopt where the compiler would warn if None were deprecated. The intent is to reduce the amount of manual work required in migrating from Optional to std::optional. This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-08-18[Clang] Propagate const context info when emitting compound literalTies Stuij1-7/+9
This patch fixes a crash when trying to emit a constant compound literal. For C++ Clang evaluates either casts or binary operations at translation time, but doesn't pass on the InConstantContext information that was inferred when parsing the statement. Because of this, strict FP evaluation (-ftrapping-math) which shouldn't be in effect yet, then causes checkFloatingpointResult to return false, which in tryEmitGlobalCompoundLiteral will trigger an assert that the compound literal wasn't constant. The discussion here around 'manifestly constant evaluated contexts' was very helpful to me when trying to understand what LLVM's position is on what evaluation context should be in effect, together with the explanatory text in that patch itself: https://reviews.llvm.org/D87528 Reviewed By: rjmccall, DavidSpickett Differential Revision: https://reviews.llvm.org/D131555
2022-08-11Fix crash-on-valid with consteval temporary construction through list ↵Aaron Ballman1-9/+6
initialization Clang currently crashes when lowering a consteval list initialization of a temporary. This is partially working around an issue in the template instantiation code (TreeTransform::TransformCXXTemporaryObjectExpr()) that does not yet know how to handle list initialization of temporaries in all cases. However, it's also helping reduce fragility by ensuring we always have a valid QualType when trying to emit a constant expression during IR generation. Fixes #55871 Differential Revision: https://reviews.llvm.org/D131194
2022-06-29Fix miscompile with [[no_unique_address]] struct fields.Richard Smith1-2/+10
If a zero-sized field has a non-trivial initializer, it should prevent the overall struct initialization from being folded to a constant during IR generation. Don't just ignore zero-sized fields entirely in IR constant emission.
2022-04-15Fix size of flexible array initializers, and re-enable assertions.Eli Friedman1-5/+16
In D123649, I got the formula for getFlexibleArrayInitChars slightly wrong: the flexible array elements can be contained in the tail padding of the struct. Fix the formula to account for that. With the fixed formula, we run into another issue: in some cases, we were emitting extra padding for flexible arrray initializers. Fix CGExprConstant so it uses a packed struct when necessary, to avoid this extra padding. Differential Revision: https://reviews.llvm.org/D123826
2022-04-13Restrict lvalue-to-rvalue conversions in CGExprConstant.Eli Friedman1-1/+10
We were generating wrong code for cxx20-consteval-crash.cpp: instead of loading a value of a variable, we were using its address as the initializer. Found while adding code to verify the size of constant initializers. Differential Revision: https://reviews.llvm.org/D123648
2022-03-28[Clang] Implement __builtin_source_location.James Y Knight1-0/+3
This builtin returns the address of a global instance of the `std::source_location::__impl` type, which must be defined (with an appropriate shape) before calling the builtin. It will be used to implement std::source_location in libc++ in a future change. The builtin is compatible with GCC's implementation, and libstdc++'s usage. An intentional divergence is that GCC declares the builtin's return type to be `const void*` (for ease-of-implementation reasons), while Clang uses the actual type, `const std::source_location::__impl*`. In order to support this new functionality, I've also added a new 'UnnamedGlobalConstantDecl'. This artificial Decl is modeled after MSGuidDecl, and is used to represent a generic concept of an lvalue constant with global scope, deduplicated by its value. It's possible that MSGuidDecl itself, or some of the other similar sorts of things in Clang might be able to be refactored onto this more-generic concept, but there's enough special-case weirdness in MSGuidDecl that I gave up attempting to share code there, at least for now. Finally, for compatibility with libstdc++'s <source_location> header, I've added a second exception to the "cannot cast from void* to T* in constant evaluation" rule. This seems a bit distasteful, but feels like the best available option. Reviewers: aaron.ballman, erichkeane Differential Revision: https://reviews.llvm.org/D120159
2022-01-28Remove reference type when checking const structsWeverything1-0/+1
ConstStructBuilder::Finalize in CGExprConstant.ccp assumes that the passed in QualType is a RecordType. In some instances, the type is a reference to a RecordType and the reference needs to be removed first. Differential Revision: https://reviews.llvm.org/D117376
2021-12-20[Clang] Add __builtin_function_startSami Tolvanen1-0/+3
Control-Flow Integrity (CFI) replaces references to address-taken functions with pointers to the CFI jump table. This is a problem for low-level code, such as operating system kernels, which may need the address of an actual function body without the jump table indirection. This change adds the __builtin_function_start() builtin, which accepts an argument that can be constant-evaluated to a function, and returns the address of the function body. Link: https://github.com/ClangBuiltLinux/linux/issues/1353 Depends on D108478 Reviewed By: pcc, rjmccall Differential Revision: https://reviews.llvm.org/D108479
2021-12-15[CodeGen] Avoid deprecated ConstantAddress constructorNikita Popov1-2/+2
Change all uses of the deprecated constructor to pass the element type explicitly and drop it. For cases where the correct element type was not immediately obvious to me or would require a slightly larger change I'm falling back to explicitly calling getPointerElementType() for now.
2021-10-14PR52183: Don't emit code for a void-typed constant expression.Richard Smith1-0/+2
This is unnecessary in general, and wrong when the expression invokes a consteval function.
2021-10-14Fix a crash on valid consteval code.Aaron Ballman1-1/+1
Not all constants are emitted within the context of a function, so use the module's ASTContext instead because 1) that's the same as the current function ASTContext, and 2) the module can never be null. Fixes PR50787.
2021-04-10[Matrix] Implement C-style explicit type conversions for matrix types.Saurabh Jha1-0/+1
This implements C-style type conversions for matrix types, as specified in clang/docs/MatrixTypes.rst. Fixes PR47141. Reviewed By: fhahn Differential Revision: https://reviews.llvm.org/D99037
2021-01-22[CGExpr] Use getCharWidth() more consistently in CCGExprConstant. NFCBjorn Pettersson1-3/+3
Most of CGExprConstant.cpp is using the CharUnits abstraction and is using getCharWidth() (directly of indirectly) when converting between size of a char and size in bits. This patch is making that abstraction more consistent by adding CharTy to the CodeGenTypeCache (honoring getCharWidth() when mapping from char to LLVM IR types, instead of using Int8Ty directly). Reviewed By: rjmccall Differential Revision: https://reviews.llvm.org/D94979
2021-01-20Revert "Following up on PR48517, fix handling of template arguments that refer"Hans Wennborg1-5/+5
Combined with 'da98651 - Revert "DR2064: decltype(E) is only a dependent', this change (5a391d3) caused verifier errors when building Chromium. See https://crbug.com/1168494#c1 for a reproducer. Additionally it reverts changes that were dependent on this one, see below. > Following up on PR48517, fix handling of template arguments that refer > to dependent declarations. > > Treat an id-expression that names a local variable in a templated > function as being instantiation-dependent. > > This addresses a language defect whereby a reference to a dependent > declaration can be formed without any construct being value-dependent. > Fixing that through value-dependence turns out to be problematic, so > instead this patch takes the approach (proposed on the core reflector) > of allowing the use of pointers or references to (but not values of) > dependent declarations inside value-dependent expressions, and instead > treating template arguments as dependent if they evaluate to a constant > involving such dependent declarations. > > This ends up affecting a bunch of OpenMP tests, due to OpenMP > imprecisely handling instantiation-dependent constructs, bailing out > early instead of processing dependent constructs to the extent possible > when handling the template. > > Previously committed as 8c1f2d15b826591cdf6bd6b468b8a7d23377b29e, and > reverted because a dependency commit was reverted. This reverts commit 5a391d38ac6c561ba908334d427f26124ed9132e. It also restores clang/test/SemaCXX/coroutines.cpp to its state before da986511fb9da1a46a0ca4dba2e49e2426036303. Revert "[c++20] P1907R1: Support for generalized non-type template arguments of scalar type." > Previously committed as 9e08e51a20d0d2b1c5724bb17e969d036fced4cd, and > reverted because a dependency commit was reverted. This incorporates the > following follow-on commits that were also reverted: > > 7e84aa1b81e72d44bcc58ffe1731bfc7abb73ce0 by Simon Pilgrim > ed13d8c66781b50ff007cb089c5905f9bb9e8af2 by me > 95c7b6cadbc9a3d4376ef44edbeb3c8bb5b8d7fc by Sam McCall > 430d5d8429473c2b10b109991d7577a3cea41140 by Dave Zarzycki This reverts commit 4b574008aef5a7235c1f894ab065fe300d26e786. Revert "[msabi] Mangle a template argument referring to array-to-pointer decay" > [msabi] Mangle a template argument referring to array-to-pointer decay > applied to an array the same as the array itself. > > This follows MS ABI, and corrects a regression from the implementation > of generalized non-type template parameters, where we "forgot" how to > mangle this case. This reverts commit 18e093faf726d15f210ab4917142beec51848258.
2021-01-18[c++20] P1907R1: Support for generalized non-type template arguments of ↵Richard Smith1-5/+5
scalar type. Previously committed as 9e08e51a20d0d2b1c5724bb17e969d036fced4cd, and reverted because a dependency commit was reverted. This incorporates the following follow-on commits that were also reverted: 7e84aa1b81e72d44bcc58ffe1731bfc7abb73ce0 by Simon Pilgrim ed13d8c66781b50ff007cb089c5905f9bb9e8af2 by me 95c7b6cadbc9a3d4376ef44edbeb3c8bb5b8d7fc by Sam McCall 430d5d8429473c2b10b109991d7577a3cea41140 by Dave Zarzycki
2020-12-22Revert "[c++20] P1907R1: Support for generalized non-type template arguments ↵Arthur Eubanks1-5/+5
of scalar type." This reverts commit 9e08e51a20d0d2b1c5724bb17e969d036fced4cd. This is part of 5 commits being reverted due to https://crbug.com/1161059. See bug for repro.
2020-12-18[c++20] P1907R1: Support for generalized non-type template arguments of ↵Richard Smith1-5/+5
scalar type.
2020-10-21[c++20] For P0732R2 / P1907R1: Basic frontend support for class types asRichard Smith1-0/+3
non-type template parameters. Create a unique TemplateParamObjectDecl instance for each such value, representing the globally unique template parameter object to which the template parameter refers. No IR generation support yet; that will follow in a separate patch.
2020-10-19Properly track whether a variable is constant-initialized.Richard Smith1-1/+1
This fixes miscomputation of __builtin_constant_evaluated in the initializer of a variable that's not usable in constant expressions, but is readable when constant-folding. If evaluation of a constant initializer fails, we throw away the evaluated result instead of keeping it as a non-constant-initializer value for the variable, because it might not be a correct value. To avoid regressions for initializers that are foldable but not formally constant initializers, we now try constant-evaluating some globals in C++ twice: once to check for a constant initializer (in an mode where is_constannt_evaluated returns true) and again to determine the runtime value if the initializer is not a constant initializer.
2020-10-13[Fixed Point] Add fixed-point to floating point cast types and consteval.Bevin Hansson1-0/+2
Reviewed By: leonardchan Differential Revision: https://reviews.llvm.org/D86631
2020-10-12Canonicalize declaration pointers when forming APValues.Richard Smith1-0/+4
References to different declarations of the same entity aren't different values, so shouldn't have different representations. Recommit of e6393ee813178e9d3306b8e3c6949a4f32f8a2cb, most recently reverted in 9a33f027ac7d73e14ae287e78ab554142d1cbc8f due to a bug caused by ObjCInterfaceDecls not propagating availability attributes along their redeclaration chains; that bug was fixed in e2d4174e9c66251d1b408234b53f53d0903c0285.
2020-10-12Revert "Canonicalize declaration pointers when forming APValues."Arthur Eubanks1-4/+0
This reverts commit 9dcd96f728863d40d6f5922ed52732fdd728fb5f. See https://crbug.com/1134762.
2020-09-27Canonicalize declaration pointers when forming APValues.Richard Smith1-0/+4
References to different declarations of the same entity aren't different values, so shouldn't have different representations. Recommit of e6393ee813178e9d3306b8e3c6949a4f32f8a2cb with fixed handling for weak declarations. We now look for attributes on the most recent declaration when determining whether a declaration is weak. (Second recommit with further fixes for mishandling of weak declarations. Our behavior here is fundamentally unsound -- see PR47663 -- but this approach attempts to not make things worse.)
2020-09-24Remove dead branch identified by @rsmith on post-commit for D88236Erich Keane1-9/+0
2020-09-24[PR47636] Fix tryEmitPrivate to handle non-constantarraytypesErich Keane1-9/+7
As mentioned in the bug report, tryEmitPrivate chokes on the MaterializeTemporaryExpr in the reproducers, since it assumes that if there are elements, than it must be a ConstantArrayType. However, the MaterializeTemporaryExpr (which matches exactly the AST when it is NOT a global/static) has an incomplete array type. This changes the section where the number-of-elements is non-zero to properly handle non-CAT types by just extracting it as an array type (since all we needed was the element type out of it).
2020-06-30[c++20] consteval functions don't get vtable slots.Richard Smith1-1/+1
For the Itanium C++ ABI, this implements the rule added in https://github.com/itanium-cxx-abi/cxx-abi/pull/83 For the MS C++ ABI, this implements the direction that seemed most plausible based on personal correspondence with MSVC developers, but is subject to change as they decide their ABI rule.
2020-06-15attempt to fix failing buildbots after 3bab88b7baa20b276faaee0aa7ca87f636c91877Tyker1-0/+18
Prevent IR-gen from emitting consteval declarations Summary: with this patch instead of emitting calls to consteval function. the IR-gen will emit a store of the already computed result.