Specifically, when we have this situation:
struct A {
template <typename T> struct B {
int m1 = sizeof(A);
};
B<int> m2;
};
We can't parse m1's initializer eagerly because we need A to be
complete. Therefore we wait until the end of A's class scope to parse
it. However, we can trigger instantiation of B before the end of A,
which will attempt to instantiate the field decls eagerly, and it would
build a bad field decl instantiation that said it had an initializer but
actually lacked one.
Fixed by deferring instantiation of default member initializers until
they are needed during constructor analysis. This addresses a long
standing FIXME in the code.
Fixes PR19195.
Reviewed By: rsmith
Differential Revision: http://reviews.llvm.org/D5690
llvm-svn: 222192
For namespaces, this is consistent with mangling and GCC's debug info
behavior. For structs, GCC uses <anonymous struct> but we prefer
consistency between all anonymous entities but don't want to confuse
them with template arguments, etc, so we'll just go with parens in all
cases.
llvm-svn: 205398
Since "half" is an OpenCL keyword and clang accepts __fp16 as an extension for
other languages, error messages and metadata (and hence debug info) should refer
to the half-precision floating point as "__fp16" instead of "half" when
compiling for non-OpenCL languages. This patch creates a new printing policy for
half in a similar manner to what is done for bool and wchar_t.
Differential Revision: http://llvm-reviews.chandlerc.com/D2952
llvm-svn: 204164
null comparison when the pointer is known to be non-null.
This catches the array to pointer decay, function to pointer decay and
address of variables. This does not catch address of function since this
has been previously used to silence a warning.
Pointer to bool conversion is under -Wbool-conversion.
Pointer to null comparison is under -Wtautological-pointer-compare, a sub-group
of -Wtautological-compare.
void foo() {
int arr[5];
int x;
// warn on these conditionals
if (foo);
if (arr);
if (&x);
if (foo == null);
if (arr == null);
if (&x == null);
if (&foo); // no warning
}
llvm-svn: 202216
The problem here is more serious than the fix implies. Adding a field
to a class updates the triviality bits for the class (among other
things). Failing to require a complete type before adding the field
meant that these updates don't happen in the well-formed case where
the capture is an uninstantiated class template specialization,
leading the lambda itself to be treated as having a trivial copy
constructor when it shouldn't. Fixes <rdar://problem/15560464>.
llvm-svn: 197623
This patch was submitted to the list for review and didn't receive a LGTM.
(In fact one explicit objection and one query were raised.)
This reverts commit r197295.
llvm-svn: 197299
The tests were perhaps made too relaxed in r197164 when we switched to the new
MinGW ABI. This makes sure we check explicitly for an optional thiscall
attribute and nothing else.
We should still look into whether we should print these attributes at all in
these cases.
llvm-svn: 197252
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
A previous attempt http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20130930/090049.html resulted in PR 17476, and was reverted,
The original TransformLambdaExpr (pre generic-lambdas) transformed the TypeSourceInfo of the Call operator in its own instantiation scope via TransformType. This resulted in the parameters of the call operator being mapped to their transformed counterparts in an instantiation scope that would get popped off.
Then a call to TransformFunctionParameters would add the parameters and their transformed mappings (but newly created ones!) to the current instantiation scope. This would result in a disconnect between the new call operator's TSI parameters and those used to construct the call operator declaration. This was ok in the non-generic lambda world - but would cause issues with nested transformations (when non-generic and generics were interleaved) in the generic lambda world - that I somewhat kludged around initially - but this resulted in PR17476.
The new approach seems cleaner. We only do the transformation of the TypeSourceInfo - but we make sure to do it in the current instantiation scope so we don't lose the untransformed to transformed mappings of the ParmVarDecls when they get created.
Another attempt caused a test to fail (http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20131021/091533.html) and also had to be reverted - my apologies - in my haste, i did not run all the tests - argh!
Now all the tests seem to pass - but a Fixme has been added - since I suspect Richard will find the fix a little inelegant ;) I shall try and work on a more elegant fix once I have had a chance to discuss with Richard or Doug at a later date.
Hopefully the third time;s a charm *fingers crossed*
This does not yet include capturing.
Please see test file for examples.
This patch was LGTM'd by Doug:
http://llvm-reviews.chandlerc.com/D1784
llvm-svn: 193230
They were causing CodeGenCXX/mangle-exprs.cpp to fail.
Revert "Remove the circular reference to LambdaExpr in CXXRecordDecl."
Revert "Again: Teach TreeTransform and family how to transform generic lambdas nested within templates and themselves."
llvm-svn: 193226
lambdas nested within templates and themselves.
A previous attempt http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20130930/090049.html resulted in PR 17476, and was reverted,
The original TransformLambdaExpr (pre generic-lambdas) transformed the TypeSourceInfo of the Call operator in its own instantiation scope via TransformType. This resulted in the parameters of the call operator being mapped to their transformed counterparts in an instantiation scope that would get popped off.
Then a call to TransformFunctionParameters would add the parameters and their transformed mappings (but newly created ones!) to the current instantiation scope. This would result in a disconnect between the new call operator's TSI parameters and those used to construct the call operator declaration. This was ok in the non-generic lambda world - but would cause issues with nested transformations (when non-generic and generics were interleaved) in the generic lambda world - that I somewhat kludged around initially - but this resulted in PR17476.
The new approach seems cleaner. We only do the transformation of the TypeSourceInfo - but we make sure to do it in the current instantiation scope so we don't lose the untransformed to transformed mappings of the ParmVarDecls when they get created.
This does not yet include capturing.
Please see test file for examples.
This patch was LGTM'd by Doug:
http://llvm-reviews.chandlerc.com/D1784
llvm-svn: 193216
An invalid decltype expression like 'decltype int' gives:
error: expected '(' after 'decltype'
This makes it so 'sizeof int' gives a similar one:
error: expected parentheses around type name in sizeof expression
llvm-svn: 192258
This does not yet include capturing (that is next).
Please see test file for examples.
This patch was LGTM'd by Doug:
http://llvm-reviews.chandlerc.com/D1784http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20130930/090048.html
When I first committed this patch - a bunch of buildbots were unable to compile the code that VS2010 seemed to compile. Seems like there was a dependency on Sema/Template.h which VS did not seem to need, but I have now added for the other compilers. It still compiles on Visual Studio 2010 - lets hope the buildbots remain quiet (please!)
llvm-svn: 191879
This does not yet include capturing (that is next).
Please see test file for examples.
This patch was LGTM'd by Doug:
http://llvm-reviews.chandlerc.com/D1784
llvm-svn: 191875
The general strategy is to create template versions of the conversion function and static invoker and then during template argument deduction of the conversion function, create the corresponding call-operator and static invoker specializations, and when the conversion function is marked referenced generate the body of the conversion function using the corresponding static-invoker specialization. Similarly, Codegen does something similar - when asked to emit the IR for a specialized static invoker of a generic lambda, it forwards emission to the corresponding call operator.
This patch has been reviewed in person both by Doug and Richard. Richard gave me the LGTM.
A few minor changes:
- per Richard's request i added a simple check to gracefully inform that captures (init, explicit or default) have not been added to generic lambdas just yet (instead of the assertion violation).
- I removed a few lines of code that added the call operators instantiated parameters to the currentinstantiationscope. Not only did it not handle parameter packs, but it is more relevant in the patch for nested lambdas which will follow this one, and fix that problem more comprehensively.
- Doug had commented that the original implementation strategy of using the TypeSourceInfo of the call operator to create the static-invoker was flawed and allowed const as a member qualifier to creep into the type of the static-invoker. I currently kludge around it - but after my initial discussion with Doug, with a follow up session with Richard, I have added a FIXME so that a more elegant solution that involves the use of TrivialTypeSourceInfo call followed by the correct wiring of the template parameters to the functionprototypeloc is forthcoming.
Thanks!
llvm-svn: 191634
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
been an oversight, as it definitely works. Every test which changed had
the const written on the LHS of the auto already.
Notably, this also makes things like cpp11-migrate's formation of 'const
auto &' variables much more familiar.
Yes, many people feel that 'const' and other qualifiers belong on the
RHS of the type. I'm not going to argue about that because Clang already
*overwhelming* places the qualifiers on the LHS when it can and on the
RHS when it must. We shouldn't diverge for auto. We should add a tool to
clang-tidy that fixes this in either direction, and then wire up
clang-tidy to tools like cpp11-migrate to fix their placement after
transforms.
llvm-svn: 189769
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- nested lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
As an example of what compiles:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Augment AutoType's constructor (similar to how variadic
template-type-parameters ala TemplateTypeParmDecl are implemented) to
accept an IsParameterPack to encode a generic lambda parameter pack.
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that Sema::ActOnLambdaAutoParameter may use it to create the
appropriate list of corresponding TemplateTypeParmDecl for each
auto parameter identified within the generic lambda (also stored
within the current LambdaScopeInfo). Additionally,
a TemplateParameterList data-member was added to hold the invented
TemplateParameterList AST node which will be much more useful
once we teach TreeTransform how to transform generic lambdas.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- Teach Sema::ActOnStartOfLambdaDefinition to set the
return type of a lambda without a trailing return type
to 'auto' in C++1y mode, and teach the return type
deduction machinery in SemaStmt.cpp to process either
C++11 and C++14 lambda's correctly depending on the flag.
- various tests were added - but much more will be needed.
A greatful thanks to all reviewers including Eli Friedman,
James Dennett and the ever illuminating Richard Smith. And
yet I am certain that I have allowed unidentified bugs to creep in;
bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 188977
function: it can't be 'void' and it can't be an initializer list. We give a
hard error for these rather than treating them as undefined behavior (we can
and probably should do the same for non-POD types in C++11, but as of this
change we don't).
Slightly rework the checking of variadic arguments in a function with a format
attribute to ensure that certain kinds of format string problem (non-literal
string, too many/too few arguments, ...) don't suppress this error.
llvm-svn: 187735
This patch essentially removes all the FIXMEs following calls to DeduceTemplateArguments() that want to keep track of deduction failure info.
llvm-svn: 186730
Make sure we properly treat names defined inside a block as local
names. There are basically three fixes here. One, correctly
treat blocks as a context where we need to use local-name mangling using
the new isLocalContainerContext helper. Two, make
CXXNameMangler::manglePrefix handle local names in a consistent way.
Three, extend CXXNameMangler::mangleLocalName so it can mangle a block
correctly.
llvm-svn: 185450
This commit rearranges the logic in CXXNameMangler::mangleLocalName and
GetLocalClassDecl so that it doesn't accidentally skip over lambdas. It
also reduces code duplication a bit.
llvm-svn: 185402
Blocks, like lambdas, can be written in contexts which are required to be
treated as the same under ODR. Unlike lambdas, it isn't possible to actually
take the address of a block, so the mangling of the block itself doesn't
matter. However, objects like static variables inside a block do need to
be mangled in a consistent way.
There are basically three components here. One, block literals need a
consistent numbering. Two, objects/types inside a block literal need
to be mangled using it. Three, objects/types inside a block literal need
to have their linkage computed correctly.
llvm-svn: 185372
This changes the mangling of local static variables/etc. inside blocks
to do something simple and sane. This avoids depending on the way we mangle
blocks, which isn't really appropriate here.
John, please take a look at this to make sure the mangling I chose is sane.
Fixes <rdar://problem/14074423>.
llvm-svn: 184780
the result of a cast-to-reference-type lifetime-extends the object to which the
reference inside the cast binds.
This requires us to look for subobject adjustments on both the inside and the
outside of the MaterializeTemporaryExpr when looking for a temporary to
lifetime-extend (which we also need for core issue 616, and possibly 1213).
llvm-svn: 184024
places which weren't setting it up properly. This allows us to get the right
cv-qualifiers for 'this' when it appears outside a method body in a class
template.
llvm-svn: 183483
materialized temporary with the corresponding MaterializeTemporaryExpr. This is
groundwork for providing C++11's guaranteed static initialization for global
references bound to lifetime-extended temporaries (if the initialization is a
constant expression).
In passing, fix a couple of bugs where some evaluation failures didn't trigger
diagnostics, and a rejects-valid where potential constant expression testing
would assume that it knew the dynamic type of *this and would reject programs
which relied on it being some derived type.
llvm-svn: 183093
a FieldDecl from it, and propagate both into the closure type and the
LambdaExpr.
You can't do much useful with them yet -- you can't use them within the body
of the lambda, because we don't have a representation for "the this of the
lambda, not the this of the enclosing context". We also don't have support or a
representation for a nested capture of an init-capture yet, which was intended
to work despite not being allowed by the current standard wording.
llvm-svn: 181985
- References to ObjC bit-field ivars are bit-field lvalues;
fixes rdar://13794269, which got me started down this.
- Introduce Expr::refersToBitField, switch a couple users to
it where semantically important, and comment the difference
between this and the existing API.
- Discourage Expr::getBitField by making it a bit longer and
less general-sounding.
- Lock down on const_casts of bit-field gl-values until we
hear back from the committee as to whether they're allowed.
llvm-svn: 181252
C++1y, so stop adding the 'const' there. Provide a compatibility warning for
code relying on this in C++11, with a fix-it hint. Update our lazily-written
tests to add the const, except for those ones which were testing our
implementation of this rule.
llvm-svn: 179969
it apart from [[gnu::noreturn]] / __attribute__((noreturn)), since their
semantics are not equivalent (for instance, we treat [[gnu::noreturn]] as
affecting the function type, whereas [[noreturn]] does not).
llvm-svn: 172691
We don't support any C++11 attributes that appertain to declaration specifiers so reject
the attributes in parser until we support them; this also conforms to what g++ 4.8 is doing.
llvm-svn: 167481
Rather than adding a ContainsUnexpandedParameterPack bit to essentially every
AST node, we tunnel the bit directly up to the surrounding lambda expression
when we reach a context where an unexpanded pack can not normally appear.
Thus any statement or declaration within a lambda can now potentially contain
an unexpanded parameter pack.
llvm-svn: 160705
literal helper functions. All helper functions (global
and locals) use block_invoke as their prefix. Local literal
helper names are prefixed by their enclosing mangled function
names. Blocks in non-local initializers (e.g. a global variable
or a C++11 field) are prefixed by their mangled variable name.
The descriminator number added to end of the name starts off
with blank (for first block) and _<N> (for the N+2-th block).
llvm-svn: 159206
lambda as referring to a local in an enclosing scope if we're in the
enclosing scope of the lambda (not it's function call operator). Also,
turn the test into an IR generation test, since that's where the
crashes occurred. Really fixes PR12746 / <rdar://problem/11465120>.
llvm-svn: 156926
Moves the bool bail-out down a little in SemaChecking - so now
-Wnull-conversion and -Wliteral-conversion can fire when the target type is
bool.
Also improve the wording/details in the -Wliteral-conversion warning to match
the -Wconstant-conversion.
llvm-svn: 156826
exception specifications on member functions until after the closing
'}' for the containing class. This allows, for example, a member
function to throw an instance of its own class. Fixes PR12564 and a
fairly embarassing oversight in our C++98/03 support.
llvm-svn: 154844
in the declaration of a non-static member function after the
(optional) cv-qualifier-seq, which in practice means in the exception
specification and late-specified return type.
The new scheme here used to manage 'this' outside of a member function
scope is more general than the Scope-based mechanism previously used
for non-static data member initializers and late-parsesd attributes,
because it can also handle the cv-qualifiers on the member
function. Note, however, that a separate pass is required for static
member functions to determine whether 'this' was used, because we
might not know that we have a static function until after declaration
matching.
Finally, this introduces name mangling for 'this' and for the implicit
'this', which is intended to match GCC's mangling. Independent
verification for the new mangling test case would be appreciated.
Fixes PR10036 and PR12450.
llvm-svn: 154799
* s/nonstatic/non-static/ in the diagnostics, since the latter form outvoted
the former by 28-2 in our diagnostics.
* Fix the "use of member in static member function" diagnostic to correctly
detect this situation inside a block or lambda.
* Produce a more specific "invalid use of non-static member" diagnostic for
the case where a nested class member refers to a member of a
lexically-surrounding class.
llvm-svn: 154073
early, since their values can be used in constant expressions in C++11. For
odr-use checking, the opposite change is required, since references are
odr-used whether or not they satisfy the requirements for appearing in a
constant expression.
llvm-svn: 151881
lambda closure type's function pointer conversion over user-defined
conversion via a lambda closure type's block pointer conversion,
always. This is a preference for more-standard code (since blocks
are an extension) and a nod to efficiency, since function pointers
don't require any memory management. Fixes PR12063.
llvm-svn: 151170
block pointer that returns a block literal which captures (by copy)
the lambda closure itself. Some aspects of the block literal are left
unspecified, namely the capture variable (which doesn't actually
exist) and the body (which will be filled in by IRgen because it can't
be written as an AST).
Because we're switching to this model, this patch also eliminates
tracking the copy-initialization expression for the block capture of
the conversion function, since that information is now embedded in the
synthesized block literal. -1 side tables FTW.
llvm-svn: 151131
that 'this' can be used in the brace-or-equal-initializer of a
non-static data member, and C++11 [expr.prim.lambda]p9, which says
that lambda expressions not in block scope can have no captures, side
fully with C++11 [expr.prim.general]p4 by allowing 'this' to be
captured within these initializers. This seems to be the intent of
non-static data member initializers.
llvm-svn: 151101
arguments. There are two aspects to this:
- Make sure that when marking the declarations referenced in a
default argument, we don't try to mark local variables, both because
it's a waste of time and because the semantics are wrong: we're not
in a place where we could capture these variables again even if it
did make sense.
- When a lambda expression occurs in a default argument of a
function template, make sure that the corresponding closure type is
considered dependent, so that it will get properly instantiated. The
second bit is a bit of a hack; to fix it properly, we may have to
rearchitect our handling of default arguments, parsing them only
after creating the function definition. However, I'd like to
separate that work from the lambdas work.
llvm-svn: 151076
eliminating a bunch of redundant code and properly modeling how the
captures of outside blocks/lambdas affect the types seen by inner
captures.
This new scheme makes two passes over the capturing scope stack. The
first pass goes up the stack (from innermost to outermost), assessing
whether the capture looks feasible and stopping when it either hits
the scope where the variable is declared or when it finds an existing
capture. The second pass then walks down the stack (from outermost to
innermost), capturing the variable at each step and updating the
captured type and the type that an expression referring to that
captured variable would see. It also checks type-specific
restrictions, such as the inability to capture an array within a
block. Note that only the first odr-use of each
variable needs to do the full walk; subsequent uses will find the
capture immediately, so multiple walks need not occur.
The same routine that builds the captures can also compute the type of
the captures without signaling errors and without actually performing
the capture. This functionality is used to determine the type of
declaration references as well as implementing the weird decltype((x))
rule within lambda expressions.
The capture code now explicitly takes sides in the debate over C++
core issue 1249, which concerns the type of captures within nested
lambdas. We opt to use the more permissive, more useful definition
implemented by GCC rather than the one implemented by EDG.
llvm-svn: 150875
even if they are not within a function scope. Teach template
instantiation to treat them as such, and make sure that we have a
local instantiation scope when instantiating default arguments and
static data members.
llvm-svn: 150725
pointers and block pointers). We use dummy definitions to keep the
invariant that an implicit, used definition has a body; IR generation
will substitute the actual contents, since they can't be represented
as C++.
For the block pointer case, compute the copy-initialization needed to
capture the lambda object in the block, which IR generation will need
later.
llvm-svn: 150645
function, provide a specialized diagnostic that indicates the kind of
special member function (default constructor, copy assignment
operator, etc.) and that it was implicitly deleted. Add a hook where
we can provide more detailed information later.
llvm-svn: 150611
to be core constant expressions (including pointers and references to
temporaries), and makes constexpr calculations Turing-complete. A Turing machine
simulator is included as a testcase.
This opens up the possibilty of removing CCValue entirely, and removing some
copies from the constant evaluator in the process, but that cleanup is not part
of this change.
llvm-svn: 150557
lambda expressions. Because these issue was pulled back from Ready
status at the Kona meeting, we still emit an ExtWarn when using
default arguments for lambda expressions.
llvm-svn: 150519
expression with the original call operator, so that we don't try to
separately instantiate the call operator. Test and tweak a few more
bits for template instantiation of lambda expressions.
llvm-svn: 150440
expressions. This is mostly a simple refact, splitting the main "start
a lambda expression" function into smaller chunks that are driven
either from the parser (Sema::ActOnLambdaExpr) or during AST
transformation (TreeTransform::TransformLambdaExpr). A few minor
interesting points:
- Added new entry points for TreeTransform, so that we can
explicitly establish the link between the lambda closure type in the
template and the lambda closure type in the instantiation.
- Added a bit into LambdaExpr specifying whether it had an explicit
result type or not. We should have had this anyway.
This code is 'lightly' tested.
llvm-svn: 150417
1358, 1360, 1452 and 1453.
- Instantiations of constexpr functions are always constexpr. This removes the
need for separate declaration/definition checking, which is now gone.
- This makes it possible for a constexpr function to be virtual, if they are
only dependently virtual. Virtual calls to such functions are not constant
expressions.
- Likewise, it's now possible for a literal type to have virtual base classes.
A constexpr constructor for such a type cannot actually produce a constant
expression, though, so add a special-case diagnostic for a constructor call
to such a type rather than trying to evaluate it.
- Classes with trivial default constructors (for which value initialization can
produce a fully-initialized value) are considered literal types.
- Classes with volatile members are not literal types.
- constexpr constructors can be members of non-literal types. We do not yet use
static initialization for global objects constructed in this way.
llvm-svn: 150359
id-expression 'x' will compute the type based on the assumption that
'x' will be captured, even if it isn't captured, per C++11
[expr.prim.lambda]p18. There are two related refactors that go into
implementing this:
1) Split out the check that determines whether we should capture a
particular variable reference, along with the computation of the
type of the field, from the actual act of capturing the
variable.
2) Always compute the result of decltype() within Sema, rather than
AST, because the decltype() computation is now context-sensitive.
llvm-svn: 150347
default is '=', and reword the warning about explicitly capturing
'this' in such lambdas to indicate that only explicit capture is
banned.
Introduce Fix-Its for this and other "save the programmer from
themself" rules regarding what can be explicitly captured and what
must be implicitly captured.
llvm-svn: 150256
nested captures. We currently don't get odr-use correct in array
bounds, so that bit is commented out while we sort out what we need to
do.
llvm-svn: 150255
have finished parsing the body, so that name lookup will never find
anything within the closure type. Then, add this operator() and the
conversion function (if available) before completing the class.
llvm-svn: 150252
incomplete class type which has an overloaded operator&, it's now just
unspecified whether the overloaded operator or the builtin is used.
llvm-svn: 150234
[expr.prim.lambda]p4, including the current suggested resolution of
core isue 975, which allows multiple return statements so long as the
types match. ExtWarn when user code is actually making use of this
extension.
llvm-svn: 150168
- Complete the lambda class when we finish the lambda expression
(previously, it was left in the "being completed" state)
- Actually return the LambdaExpr object and bind to the resulting
temporary when needed.
- Detect when cleanups are needed while capturing a variable into a
lambda (e.g., due to default arguments in the copy constructor), and
make sure those cleanups apply for the whole of the lambda
expression.
llvm-svn: 150123
only add 'const' for variables captured by copy in potentially
evaluated expressions of non-mutable lambdas. (The "by copy" part was
missing).
llvm-svn: 150088
the sign bit doesn't have undefined behavior, but a signed left shift of a 1 bit
out of the sign bit still does. As promised to Howard :)
The suppression of the potential constant expression checking in system headers
is also removed, since the problem it was working around is gone.
llvm-svn: 150059
- Capturing variables by-reference and by-copy within a lambda
- The representation of lambda captures
- The creation of the non-static data members in the lambda class
that store the captured variables
- The initialization of the non-static data members from the
captured variables
- Pretty-printing lambda expressions
There are a number of FIXMEs, both explicit and implied, including:
- Creating a field for a capture of 'this'
- Improved diagnostics for initialization failures when capturing
variables by copy
- Dealing with temporaries created during said initialization
- Template instantiation
- AST (de-)serialization
- Binding and returning the lambda expression; turning it into a
proper temporary
- Lots and lots of semantic constraints
- Parameter pack captures
llvm-svn: 149977
value of class type, look for a unique conversion operator converting to
integral or unscoped enumeration type and use that. Implements [expr.const]p5.
Sema::VerifyIntegerConstantExpression now performs the conversion and returns
the converted result. Some important callers of Expr::isIntegralConstantExpr
have been switched over to using it (including all of those required for C++11
conformance); this switch brings a side-benefit of improved diagnostics and, in
several cases, simpler code. However, some language extensions and attributes
have not been moved across and will not perform implicit conversions on
constant expressions of literal class type where an ICE is required.
In passing, fix static_assert to perform a contextual conversion to bool on its
argument.
llvm-svn: 149776
* support the gcc __builtin_constant_p() ? ... : ... folding hack in C++11
* check for unspecified values in pointer comparisons and pointer subtractions
llvm-svn: 149578
This is a mess. According to the C++11 standard, pointer subtraction only has
undefined behavior if the difference of the array indices does not fit into a
ptrdiff_t.
However, common implementations effectively perform a char* subtraction first,
and then divide the result by the element size, which can cause overflows in
some cases. Those cases are not considered to be undefined behavior by this
change; perhaps they should be.
llvm-svn: 149490
- Actually building the var -> capture mapping properly (there was an off-by-one error)
- Keeping track of the source location of each capture
- Minor QoI improvements, e.g, highlighing the prior capture if
there are multiple captures, pointing at the variable declaration we
found if we reject it.
As part of this, add standard citations for the various semantic
checks we perform, and note where we're not performing those checks as
we should.
llvm-svn: 149462
values and non-type template arguments of integral and enumeration types.
This change causes some legal C++98 code to no longer compile in C++11 mode, by
enforcing the C++11 rule that narrowing integral conversions are not permitted
in the final implicit conversion sequence for the above cases.
llvm-svn: 148439
not integer constant expressions. In passing, fix the 'folding is an extension'
diagnostic to not claim we're accepting the code, since that's not true in
-pedantic-errors mode, and add this diagnostic to -Wgnu.
llvm-svn: 148209
pointer-arithmetic-related undefined behavior and unspecified results. We
continue to fold such values, but now notice they aren't constant expressions.
llvm-svn: 147659
Also temporarily remove the assumption from IR gen that we can emit IR for every
constant we can fold, since it isn't currently true in C++11, to fix PR11676.
Original comment from r147271:
constexpr: perform zero-initialization prior to / instead of performing a
constructor call when appropriate. Thanks to Eli for spotting this.
llvm-svn: 147384
Split out a new ExpressionEvaluationContext flag for this case, and don't treat
it as unevaluated in C++11. This fixes some crash-on-invalids where we would
allow references to class members in potentially-evaluated constant expressions
in static member functions, and also fixes half of PR10177.
The fix to PR10177 exposed a case where template instantiation failed to provide
a source location for a diagnostic, so TreeTransform has been tweaked to supply
source locations when transforming a type. The source location is still not very
good, but MarkDeclarationsReferencedInType would need to operate on a TypeLoc to
improve it further.
Also fix MarkDeclarationReferenced in C++98 mode to trigger instantiation for
static data members of class templates which are used in constant expressions.
This fixes a link-time problem, but we still incorrectly treat the member as
non-constant. The rest of the fix for that issue is blocked on PCH support for
early-instantiated static data members, which will be added in a subsequent
patch.
llvm-svn: 146955
variable is initialized by a non-constant expression, and pass in the variable
being declared so that earlier-initialized fields' values can be used.
Rearrange VarDecl init evaluation to make this possible, and in so doing fix a
long-standing issue in our C++ constant expression handling, where we would
mishandle cases like:
extern const int a;
const int n = a;
const int a = 5;
int arr[n];
Here, n is not initialized by a constant expression, so can't be used in an ICE,
even though the initialization expression would be an ICE if it appeared later
in the TU. This requires computing whether the initializer is an ICE eagerly,
and saving that information in PCH files.
llvm-svn: 146856
fails within a call to a constexpr function. Add -fconstexpr-backtrace-limit
argument to driver and frontend, to control the maximum number of notes so
produced (default 10). Fix APValue printing to be able to pretty-print all
APValue types, and move the testing for this functionality from a unittest to
a -verify test now that it's visible in clang's output.
llvm-svn: 146749
freebsd bots happy. In the longer term, we should have a mechanism for moving
constexpr recursion off the call stack, to support the default limit of 512
suggested by the standard.
llvm-svn: 146596
through varargs. This only happens when we're in an unevaluated
context, where we don't want to trigger an error anyway. Fixes PR11131
/ <rdar://problem/10288375>.
llvm-svn: 141986
and DefaultFunctionArrayLvalueConversion. To prevent
significant regression for should-this-be-a-call fixits,
and to repair some such regression from the introduction of
bound member placeholders, make those placeholder checks
try to build calls appropriately. Harden the build-a-call
logic while we're at it.
llvm-svn: 141738
that the unevaluated subexpressions of &&, ||, and ? : are not
considered when determining whether the expression is a constant
expression. Also, turn the "used in its own initializer" warning into
a runtime-behavior warning, so that it doesn't fire when a variable is
used as part of an unevaluated subexpression of its own initializer.
Fixes PR9999.
llvm-svn: 131968
overload, so that we actually do the resolution for full expressions
and emit more consistent, useful diagnostics. Also fixes an IRGen
crasher, where Sema wouldn't diagnose a resolvable bound member
function template-id used in a full-expression (<rdar://problem/9108698>).
llvm-svn: 127747
a scoped enumeration type to an integral or floating type,
properly. There was an over-eager assertion, and it was missing the
floating-point case.
Fixes PR9107/<rdar://problem/8937402>.
llvm-svn: 125825
- BlockDeclRefExprs always store VarDecls
- BDREs no longer store copy expressions
- BlockDecls now store a list of captured variables, information about
how they're captured, and a copy expression if necessary
With that in hand, change IR generation to use the captures data in
blocks instead of walking the block independently.
Additionally, optimize block layout by emitting fields in descending
alignment order, with a heuristic for filling in words when alignment
of the end of the block header is insufficient for the most aligned
field.
llvm-svn: 125005